2012-02-09 21 views
2

我無法弄清楚什麼是錯時指定的文件。我之前使用過重命名,沒有任何問題,並且在其他類似問題中找不到解決方案。的Python WindowsError:[錯誤3]系統找不到嘗試重新命名

import os 
import random 

directory = "C:\\whatever" 
string = "" 
alphabet = "abcdefghijklmnopqrstuvwxyz" 


listDir = os.listdir(directory) 

for item in listDir: 
    path = os.path.join(directory, item) 

    for x in random.sample(alphabet, random.randint(5,15)): 
     string += x 

    string += path[-4:] #adds file extension 

    os.rename(path, string) 
    string= "" 
+0

那麼,'os.rename(path,string)'中的'path'是否存在? – Hamish 2012-02-09 23:03:20

+2

擴展名不一定是3個字符,因此對該部分使用'os.path.splitext'。 – wim 2012-02-09 23:08:44

+0

這是更有效的BTW:'字符串=「」。加入(random.sample(字母,random.randint(5,15)))' – jdi 2012-02-09 23:15:09

回答

2

你的代碼中有一些奇怪的東西。例如,文件的源代碼是完整路徑,但重命名的目的地只是一個文件名,所以文件將出現在任何工作目錄中 - 這可能不是您想要的。

你必須從兩個隨機生成的文件名是相同的沒有保護,所以你可能會破壞你的一些數據的這種方式。

嘗試了這一點,這應該有助於您發現任何問題。這隻會重命名文件,並跳過子目錄。

import os 
import random 
import string 

directory = "C:\\whatever" 
alphabet = string.ascii_lowercase 

for item in os.listdir(directory): 
    old_fn = os.path.join(directory, item) 
    new_fn = ''.join(random.sample(alphabet, random.randint(5,15))) 
    new_fn += os.path.splitext(old_fn)[1] #adds file extension 
    if os.path.isfile(old_fn) and not os.path.exists(new_fn): 
    os.rename(path, os.path.join(directory, new_fn)) 
    else: 
    print 'error renaming {} -> {}'.format(old_fn, new_fn) 
2

如果你想保存回同一個目錄,你需要添加一個路徑到你的'string'變量。目前它只是創建一個文件名,os.rename需要一個路徑。

for item in listDir: 
    path = os.path.join(directory, item) 

    for x in random.sample(alphabet, random.randint(5,15)): 
     string += x 

    string += path[-4:] #adds file extension 
    string = os.path.join(directory,string) 

    os.rename(path, string) 
    string= "" 
+0

切換爲循環使用,用於向OP最好的建議更有效的列表比較,還必須在運行之前,你的代碼 – jdi 2012-02-09 23:21:18

+0

@jdi步行縮進錯誤。在程序正確之前不要擔心perf。這裏完全沒有問題。想想os.rename有多少時鐘?你可以用任何方式編寫這段代碼,os.rename將決定經過的時間。正確性始終是最重要的目標。 – 2012-02-09 23:26:31

+0

@DavidHeffernan - 我不同意。雖然這顯然只是一個意見。我認爲在給出答案的同時還要糾正習慣問題。循環和添加字符串是一定要解決的,以幫助OP在python中成長。因爲這個,我正在投票回答這個問題。 – jdi 2012-02-09 23:29:02

相關問題