Python:关闭和移除文件
我正在尝试解压一个文件,然后读取其中一个解压出来的文件,并删除这些解压出来的文件。
- 解压出来的文件(比如我们得到了file1和file2)
读取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)
2 个回答
3
当你使用 with
语句来处理文件时,不需要手动关闭文件句柄。文件句柄会在你离开这个代码块的时候自动关闭,也就是说,当你完成读取文件的操作后,它就会自动关闭。
你可以查看这个 Python教程 了解更多信息。
2
你看到的这些错误其实不是Python所报告的错误。它们的意思是有其他东西尝试去打开这些文件,但从你提供的这小段代码来看,很难判断具体是什么问题。
如果你只是想从一个压缩文件中获取一些数据,其实没必要把它们提取到硬盘上。你可以直接从压缩文件中读取数据,只把数据提取到内存中,使用zipfile.ZipFile.open
就可以了。