我正在使用基本文件夹REF_IMAGES
,其中我保留了指定语言的引用位图。我还有其他几种语言文件夹,例如REF_IMAGES-EN
,REF_IMAGES-NL
等。
我想创建一个脚本,将基本文件夹重命名为其语言,即。 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
我已经尝试了几个Unlocker程序,但没有它们工作。我想这是脚本阻止它本身,但我无法弄清楚是什么。
有谁知道吗? 此致
答案 0 :(得分:0)
测试:
try: currentLanguage = textFile.read() except WindowsError: pass textFile.close() try: textFile.write("%s" %currentLanguage) except WindowsError: pass textFile.close()
答案 1 :(得分: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带领我实际上。