windows中的os.remove()给出“[Error 32]正被另一个进程使用”

2024-05-21 00:56:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我知道这个问题以前也被问过很多次。我还是做不到。如果我的英语不好我很抱歉

在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是一个变量,包含文件的完整路径结构。Like wisedec_file也包含路径,但指向一个新文件。im试图删除的文件是在read mode下使用的文件。需要帮忙。

我的尝试:

  1. 尝试关闭文件my_file.close()。我得到的相应错误是AttributeError: 'str' object has no attribute 'close'。我知道,当文件在 read mode当它到达 文件。但我还是试了一下
  2. 也由os.close(my_file)根据https://stackoverflow.com/a/1470388/3869739尝试。我的错误是TypeError: an integer is required
  3. 或者,我是不是因为打开了文件才出现这个错误 两次(用于计算行数和读取文件内容),。。?

Tags: 文件ofcloseosmodemylinecontents
1条回答
网友
1楼 · 发布于 2024-05-21 00:56:20

python读取或写入文件的方法是使用with上下文。

要读取文件:

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不允许您删除文件。解决方法是使用with


此外,为了澄清其他几点:

  • 当对象被销毁时,导致流关闭的垃圾收集器。文件在完成读取后不会自动关闭。如果程序员想倒带,那就没有意义了,是吗?
  • os.close(..)在内部调用采用整数文件描述符的C-API close(..)。当你经过的时候不是字符串。

相关问题 更多 >