我知道这个问题在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)
Run Code Online (Sandbox Code Playgroud)
我的代码:
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)
Run Code Online (Sandbox Code Playgroud)
这my_file是一个包含文件完整路径结构的变量.dec_file同样明智的还包含路径,但是要包含新文件.我试图删除的文件是正在使用的文件read mode.需要一些帮助.
我的尝试:
my_file.close().我得到的相应错误是AttributeError: 'str' object has no attribute 'close'.我知道,当文件在文件
read mode结尾时自动关闭.但我还是试一试os.close(my_file)按照/sf/answers/102927191/进行了尝试.我得到了错误TypeError: an integer is requiredPythonic从文件读取或写入文件的方式是使用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.
Run Code Online (Sandbox Code Playgroud)
来写:
with open("/path/to/file", "w") as f:
print>>f, "Goodbye world"
# Outside `with` here, f.close() is automatically called.
Run Code Online (Sandbox Code Playgroud)
现在,如果没有其他进程读取或写入文件,并假设您拥有所有权限,则应该能够关闭该文件.存在资源泄漏(文件句柄未关闭)的可能性很大,因为Windows不允许您删除文件.解决方案是使用with.
此外,澄清其他几点:
close(..)带有整数文件描述符的C-API .你传递的不是字符串.| 归档时间: |
|
| 查看次数: |
16474 次 |
| 最近记录: |