我知道这个问题以前也被问过很多次。我还是做不到。如果我的英语不好我很抱歉
在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
下使用的文件。需要帮忙。
我的尝试:
my_file.close()
。我得到的相应错误是AttributeError: 'str' object has no attribute 'close'
。我知道,当文件在
read mode
当它到达
文件。但我还是试了一下os.close(my_file)
根据https://stackoverflow.com/a/1470388/3869739尝试。我的错误是TypeError: an integer is required
python读取或写入文件的方法是使用
with
上下文。要读取文件:
写作:
现在,如果没有其他进程读取或写入该文件,并且假设您拥有所有权限,则应该能够关闭该文件。很有可能存在资源泄漏(文件句柄未关闭),因此Windows不允许您删除文件。解决方法是使用
with
。此外,为了澄清其他几点:
close(..)
。当你经过的时候不是字符串。相关问题 更多 >
编程相关推荐