2017-03-09 503 views
0

我正在使用python 2.7x。我对python很陌生,非常感谢你的帮助。我已经看了很多帖子,包括如下图所示,仅举几例关于此错误的:重命名txt文件。编辑版本:[错误183]当该文件已存在时无法创建文件

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:名字 '重命名' 没有定义,而不是...:/

等等等等

试图纠正我的代码,我以后米仍然得到相同的错误。

我想这样做的是:我读的目录中的文件,如果任何文件包含一个特定的字符串,我会重新命名该文本文件

(即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) 

INITIAL版本:我得到的错误是在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() 

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

回答

1

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

相反,你应该在重命名文件之前调用

abc.close() 

有关更多信息,请参见this link有关文件I/O。

+0

这是这个或其他进程正在访问您的文件。 –

+0

我试图把abc。关闭()之前的句子“for fname:”,但我得到了错误:“”在abc中的行: ValueError:关闭文件上的I/O操作“” – Sandy

+0

任何想法可能是其他进程? @PrajjwalSrivastav – Sandy

相关问题