我正在尝试解压缩文件,并读取其中一个解压缩的文件,并删除提取的文件。
读取file1,然后关闭它。
with open(file1, 'r') as f:
data = f.readline()
f.close()
使用“数据”执行某些操作。
删除提取的文件。
os.remove(file1)
一切都很顺利,除了最后收到这些消息。这些文件也被删除了。如何正确关闭文件?
/tmp/file1: No such file or directory
140347508795048:error:02001002:system library:fopen:No such file or directory:bss_file.c:398:fopen('/tmp/file1','r')
140347508795048:error:20074002:BIO routines:FILE_CTRL:system lib:bss_file.c:400:
更新 (我的脚本看起来与这些相似)
#!/usr/bin/python
import subprocess, os
infile = "filename.enc"
outfile = "filename.dec"
opensslCmd = "openssl enc -a -d -aes-256-cbc -in %s -out %s" % (infile, outfile)
subprocess.Popen(opensslCmd, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, close_fds=True)
os.remove(infile)
答案 0 :(得分:3)
将with
与file
上下文管理器一起使用时,无需关闭文件句柄,当范围发生变化时(即读取线完成时),句柄会自动关闭。
答案 1 :(得分:2)
您看到的错误不是错误,因为Python会报告错误。它们意味着Python以外的其他东西试图打开这些文件,虽然很难从你的小片段中分辨出来。
如果您只是尝试从zip文件中检索某些数据,则没有理由将它们提取到磁盘。您可以直接从zip文件中读取数据,仅使用zipfile.ZipFile.open
提取到内存。