【发布时间】:2017-07-29 20:46:22
【问题描述】:
我正在使用 python 2.7x。我对 python 很陌生,非常感谢你的帮助。我已经阅读了许多帖子,包括下面显示的关于此错误的一些帖子:
WindowsError: [Error 32] The process cannot access the file because it is being used by another process: 'new.dat' --> 我的文件关闭指令已经结束了。
python 2 [Error 32] The process cannot access the file because it is being used by another process --> 我无法使用 shutil,因为我正在使用的 python 程序中有一些错误,并且我无法编辑路径,因为我的计算机受到管理保护。
Rename Files in Python -->按照建议后,我得到了 NameError: name 'rename' is not defined...:/
等等等等
在尝试纠正我的代码后,我仍然收到同样的错误。
我想做的是:我读取目录中的文件,如果任何文件包含特定字符串,我将重命名文本文件 (即 first.txt 到 firstfound.txt。)
编辑版本: 在重命名文件之前,我尝试移动 abc.close():
import os
fname = raw_input("Enter file name: ")
#fill in file directory here
abc = open(fname)
for line in abc:
if not line.find("scramble") :
continue
oldfile = fname
abc.close()
if oldfile == fname:
for title in fname:
endname = title.find('.txt')
oldtitle = title[:endname]
newfile = oldtitle +"found.txt"
os.rename(oldfile,newfile)
但我在最后一行出现了这个错误。 os.rename(旧文件,新文件) WindowsError:[错误 183] 当文件已存在时无法创建该文件。我的文件夹中没有新名称的文件。 非常感谢您的建议!
编辑版本 2:我也尝试过这组代码,但它给了我 WindowsError:[错误 5] 访问被拒绝。请问有没有因为没有管理员权限而无法重命名txt文件的情况?谢谢!
import os
fname = raw_input("Enter file name: ")
#fill in file directory here
abc = open(fname)
for line in abc:
if not line.find("scramble") :
continue
oldfile = fname
abc.close()
if (oldfile == fname): #+'/' + "a.txt"
for title in fname:
endname = title.find('.txt')
oldtitle = title[:endname]
new_file = oldtitle +'/' + "a.txt"
os.rename(fname,new_file)
初始版本:我得到的错误是在 os.rename 行。 "WindowsError: [错误 32] 进程无法访问该文件,因为它正被另一个进程使用"
我的整个程序代码如下图:
import os
fname = raw_input("Enter file name: ")
#fill in file directory here
abc = open(fname)
for line in abc:
if not line.find("scramble") :
continue
old_file = fname
for title in fname:
endname = title.find('.txt')
oldtitle = title[:endname]
new_file = oldtitle +'/' + "found.txt"
os.rename(old_file,new_file) ##WindowsError: [Error 32] The process cannot access the file because it is being used by another process
abc.close()
我不明白为什么这个错误仍然存在。 (我已关闭所有文件和文件夹)。非常感谢!
【问题讨论】:
标签: python python-2.7 file-rename windowserror