0

我正在使用 python 2.7x。我对 python 很陌生,非常感谢你的帮助。我已经阅读了许多帖子,包括下面显示的关于此错误的一些帖子:

WindowsError:[错误 32] 进程无法访问该文件,因为它正被另一个进程使用:'new.dat' --> 我的文件关闭指令已经结束。

python 2 [错误 32] 该进程无法访问该文件,因为它正在被另一个进程使用--> 我无法使用 shutil,因为我正在使用的 python 程序中有一些错误,我无法像我的计算机一样编辑路径受行政保护。

在 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(oldfile,newfile) 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() 

我不明白为什么这个错误仍然存​​在。(我已关闭所有文件和文件夹)。非常感谢!

4

1 回答 1

1

问题很可能是由于您在代码中调用了 open() 。python中的open()函数打开文件文件进行读/写,所以如果你打开一个文件,那么你不能在它上面调用rename,因为它是在另一个位置打开的。

相反,你应该打电话

abc.close() 

在重命名文件之前。

有关文件 I/O 的更多信息,请参阅此链接

于 2017-03-09T02:47:59.470 回答