首页 > 解决方案 > 如何为所有文件和相关文件夹使用 unicode 字符重命名/替换特定关键字?

问题描述

'input_folder'我在一个目录'.dat'ABCMWE如下所示:

import os
import random
import errno    
#--------------------------------------
# Create random folders and files

# tzot's forced directory create hack https://stackoverflow.com/a/600612/4576447
def mkdir_p(path):
    try:
        os.makedirs(path)
    except OSError as exc:  # Python >2.5
        if exc.errno == errno.EEXIST and os.path.isdir(path):
            pass
        else:
            raise


if not os.path.isdir('./input_folder'):
    os.makedirs('input_folder')
for i in range(10):
    mkdir_p('./input_folder/folder_ABC_' + str(random.randint(100,999)))


for root, dirs, files in os.walk('./input_folder'):
    for dir in dirs:
        result = open(os.path.join(root,dir) + '/ABC ' + str(random.randint(100,999)) + '.dat','w')
        result = open(os.path.join(root,dir) + '/XYZ-ABC ' + str(random.randint(100,999)) + '.dat','w')

#--------------------------------------
# Main rename code

for root, dirs, files in os.walk('./input_folder'):
    for file in files:  
        if file.endswith((".dat")):
            os.rename(file, file.replace('ABC', u'\u2714'.encode('utf-8')))

此 MWE 给出以下错误:

os.rename(file, file.replace('ABC', u'\u2714'.encode('utf-8')))
WindowsError: [Error 2] The system cannot find the file specified

如何在 Python 2.7 中正确重命名所有具有 ABC 和 unioode 字符的文件和文件夹?

标签: pythonpython-2.7unicodeglobpython-os

解决方案


至少有五个问题:

  1. 处理 Unicode 时,请在任何地方使用它。 os.walk如果传递 Unicode 路径,将返回 Unicode 文件名。 from __future__ import unicode_literals将默认字符串为 Unicode。
  2. 打开文件时,关闭它们。稍后重命名时会遇到问题。 result仍然存在并且引用了最后打开的文件。
  3. 如评论中所述,在名称之前和之后都使用os.path.jointheroot和 the file
  4. os.walktopdown=False. _ 这将首先处理叶节点,因此目录树在遍历它时不会损坏(并且保持有效)rootdirs
  5. 首先重命名文件,然后重命名目录,以在遍历目录树时再次不损坏目录树。

结果:

from __future__ import unicode_literals

# Skipping unchanged code...

for root, dirs, files in os.walk('./input_folder'):
    for dir in dirs:
        # One way to ensure the file is closed.
        with open(os.path.join(root,dir) + '/ABC ' + str(random.randint(100,999)) + '.dat','w'):
            pass
        with open(os.path.join(root,dir) + '/XYZ-ABC ' + str(random.randint(100,999)) + '.dat','w'):
            pass

#--------------------------------------
# Main rename code

for root, dirs, files in os.walk('./input_folder',topdown=False):
    for file in files:  
        if file.endswith((".dat")):
            # Generate the full file path names.
            filename1 = os.path.join(root,file)
            filename2 = os.path.join(root,file.replace('ABC', '\u2714'))
            os.rename(filename1,filename2)
    for d in dirs:  
        # Generate the full directory path names.
        dirname1 = os.path.join(root,d)
        dirname2 = os.path.join(root,d.replace('ABC', '\u2714'))
        os.rename(dirname1,dirname2)

推荐阅读