Python:关闭和删除文件

时间:2011-06-01 08:34:56

标签: python file

我正在尝试解压缩文件,并读取其中一个解压缩的文件,并删除提取的文件。

  1. 提取的文件(例如我们得到了file1和file2)
  2. 读取file1,然后关闭它。

    with open(file1, 'r') as f:
        data = f.readline()
    f.close()
    
  3. 使用“数据”执行某些操作。

  4. 删除提取的文件。

    os.remove(file1)
    
  5. 一切都很顺利,除了最后收到这些消息。这些文件也被删除了。如何正确关闭文件?

        /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 个答案:

答案 0 :(得分:3)

withfile上下文管理器一起使用时,无需关闭文件句柄,当范围发生变化时(即读取线完成时),句柄会自动关闭。

请参阅python tutorial

答案 1 :(得分:2)

您看到的错误不是错误,因为Python会报告错误。它们意味着Python以外的其他东西试图打开这些文件,虽然很难从你的小片段中分辨出来。

如果您只是尝试从zip文件中检索某些数据,则没有理由将它们提取到磁盘。您可以直接从zip文件中读取数据,仅使用zipfile.ZipFile.open提取到内存。