os.remove()在Windows中给出“被另一个进程使用”

我知道这个问题已经在SO和其他地方安静了许多。 我仍然无法完成。 如果我的英语不好,我很抱歉

在Linux中删除文件要简单得多。 只是os.remove(my_file)做了这个工作,但在Windows提供

  os.remove(my_file) WindowsError: [Error 32] The process cannot access the file because it is being used by another process: (file-name) 

我的代码:

 line_count = open(my_file, mode='r') # t_lines = len(line_count.readlines()) # For total no of lines outfile = open(dec_file, mode='w') with open(my_file, mode='r') as contents: p_line = 1 line_infile = contents.readline()[4:] while line_infile: dec_of_line = baseconvert(line_infile.rstrip(),base16,base10) if p_line == t_lines: dec_of_line += str(len(line_infile)).zfill(2) outfile.write(dec_of_line + "\r\n") else: outfile.write(dec_of_line + "\r\n") p_line += 1 line_infile = contents.readline()[4:] outfile.close() os.remove(my_file) 

这里my_file是一个包含文件完整path结构的variables。 像明智的dec_file也包含path,但要新build一个文件。 而试图删除的文件是在read mode使用的文件。 需要一些帮助,请。

我的尝试:

  1. 尝试closures文件my_file.close() 。 我得到的相应错误是AttributeError: 'str' object has no attribute 'close' 。 我知道,当一个文件处于read mode时,它会在文件结束时自动closures。 但是我还是试了一下
  2. 也尝试通过os.close(my_file)按照https://stackoverflow.com/a/1470388/3869739 。 我得到错误TypeError: an integer is required
  3. 或者,我得到这个错误只是因为我打开了两次文件(用于计算行和读取文件内容),..?

从文件读取或写入文件的Pythonic方式是通过使用上下文。

读取文件:

 with open("/path/to/file") as f: contents = f.read() #Inside the block, the file is still open # Outside `with` here, f.close() is automatically called. 

来写:

 with open("/path/to/file", "w") as f: print>>f, "Goodbye world" # Outside `with` here, f.close() is automatically called. 

现在,如果没有其他进程读取或写入文件,并且假设您拥有所有权限,则应该可以关闭文件。 资源泄漏(文件句柄没有关闭)的机会很大,因为Windows不允许你删除文件 。 解决方法是使用。


此外,要澄清其他几点:

  • 它的垃圾收集器,导致对象被销毁时关闭流。 完整阅读后文件不会自动关闭。 如果程序员想要倒带,这是没有意义的,是吗?
  • os.close(..)内部调用接收整数文件描述符的C-API close(..) 。 没有字符串,因为你通过。