1

我正在使用一个基本文件夹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 程序,但它们都不起作用。我想是脚本本身阻止了它,但我不知道是什么。

有人知道吗 ?问候

4

2 回答 2

0

用这个测试:

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


try:
    textFile.write("%s" %currentLanguage)
except WindowsError:
   pass
   textFile.close()
于 2013-03-28T15:34:03.803 回答
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,实际上是他带领我。

于 2013-04-02T08:49:09.177 回答