'''想要重命名文件,刪除數組「bad_pattern」中的所有壞字符。 我通過讀取不良模式中的所有字符開始,然後與文件名中的字符進行比較。 如果它發現任何然後被替換爲「_」和循環結束文件沒有奇怪的字符返回以後使用。分配前引用的局部變量'newfile'
然後在方法moveFiles()
我應該得到預覽方法的輸出並將其保存在變量newfile
中。 最後我想重命名文件。
我收到錯誤:
local variable 'newfile' referenced before assignment
這裏是我的代碼:
file = t#est.txt
bad_pattern= ["ã", "â", "é", "è", ", "ò", "ù", "û", "~", "^", "#"","\s"]
def filename_replacer(file):
for char in bad_pattern:
for char_good in file:
if char_good == char:
newfile = file.replace(char_good, "_")
return newfile
def moveFiles():
files = os.listdir(startDir+"/"+app)
for file in files:
newfile = filename_replacer(file)
try:
os.rename(file,newfile)
except Exception as e:
print(str(e))
這不是你的實際代碼。 'file = t#est.txt'會在你看到的錯誤很久之前拋出一個錯誤,然後是'bad_pattern'。請確保您的代碼是您正在查看的準確表示。你也不會顯示被調用的函數。 – roganjosh
你是正確的,只是強迫該字符串來說明我的觀點:) 但是解決方案已經被Mark Tolonen發現 –