2017-03-09 500 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

相關問題