我正在創建我想要接受壓縮文件的軟件。由於文件是在任何地方讀取/寫入的,我創建了一個用於打開文件的實用程序函數,用於處理某些壓縮文件類型的打開/關閉。用open打開的返回文件句柄?
示例代碼:
def return_file_handle(input_file, open_mode="r"):
""" Handles compressed and uncompressed files. Accepts open modes r/w/w+ """
if input_file.endswith(".gz")
with gzip.open(input_file, open_mode) as gzipped_file_handle:
return gzipped_file_handle
的問題是,使用此代碼時,文件句柄,似乎當關閉功能的回報。我可以做我想要的東西with open
還是我需要處理關閉自己?
一下添加到上面的代碼來獲得一個最小的非工作例如:
for line in return_file_handle(input_bed, "rb"):
print line
創建一個gzip壓縮的文本文件:
echo "hei\nder!" | gzip - > test.gz
錯誤消息:
Traceback (most recent call last):
File "check_bed_against_blacklist.py", line 26, in <module>
check_bed_against_blacklist("test.gz", "bla")
File "check_bed_against_blacklist.py", line 15, in check_bed_against_blacklist
for line in return_file_handle(input_bed, "r"):
ValueError: I/O operation on closed file.
這很酷。我沒有意識到python中有多簡單的發生器。我喜歡這個答案是最好的,因爲它會在你讀完之後關閉文件。 – Alejandro 2015-03-03 06:35:58
輝煌,謝謝。謝謝其他人,我贊成你。 – 2015-03-03 08:04:42