2013-03-28 74 views
1

我正在使用一個基本文件夾REF_IMAGES其中我保留指定語言的參考位圖。我有其他幾種語言文件夾,如REF_IMAGES-ENREF_IMAGES-NLWindowsError 32試圖os.rename

我想創建一個腳本,將基本文件夾重命名爲其語言即。 REF_IMAGES-xx並將所選語言文件夾重命名爲基本文件夾名稱後。

爲此,我創建了一個txt文件,用於跟蹤文件夾中的原始語言。

我的代碼如下:

import os 

# Define paths 
baseFolder = 'D:\\IMAGES\\' 
imageFolder = 'D:\\IMAGES\\REF_IMAGES' 


LanguageFile = 'FolderLanguage.txt' 

# Define selected language 
language = '-FR' 

# Read current language of baseFolder 
textFile = open(os.path.join(imageFolder, LanguageFile), "r") 
try: 
    currentLanguage = textFile.read() 
finally: 
    textFile.close() 

# Rename image folder to original name. This where the error comes up 
os.rename(imageFolder, os.path.join(imageFolder, currentLanguage)) 

# Search for selected language folder and rename it to default one. 
for folderName in os.listdir(baseFolder): 
    if folderName.endswith(language): # Look for selected language folder 
     os.rename(os.path.join(baseFolder, folderName), os.path.join(baseFolder, folderName.split('-')[0])) # Rename selected language folder to base folder 
     currentLanguage = language # Save the language the folder is switched to 
     textFile = open(os.path.join(imageFolder, LanguageFile), "w") 
     try: 
      textFile.write("%s" %currentLanguage) 
     finally: 
      textFile.close() 

但是我碰到下面的錯誤,而試圖圖像文件夾重命名爲原來的名稱:

WindowsError: [Error 32] The process cannot access the file because it is being used by another process 

我已經試了好幾個解鎖方案,但非他們工作。我想這是腳本阻止它本身,但我無法弄清楚什麼。

有誰知道嗎? 問候

回答

0

發現問題嘍! 錯誤出現在os.rename語法中。這樣做:

os.rename(imageFolder, os.path.join(imageFolder, currentLanguage)) 

os.path.join(imageFolder, currentLanguage)輸出是IMAGES\REF_IMAGES\-FR而不是IMAGES\REF_IMAGES-FR如我所料

我現在用的語法是:

originalName = imageFolder + currentLanguage 
os.rename(imageFolder, originalName) 

感謝Mayk誰領導我的實際。

0

測試這一點:

try: 
    currentLanguage = textFile.read() 
except WindowsError: 
    pass 
    textFile.close() 


try: 
    textFile.write("%s" %currentLanguage) 
except WindowsError: 
    pass 
    textFile.close() 
+0

謝謝,但我忘了補充說,當我嘗試將文件夾重命名爲其原始名稱時出現錯誤。打開並閱讀txt文件時,我沒有任何問題。我的錯 –

相關問題