python - 如何为所有文件和相关文件夹使用 unicode 字符重命名/替换特定关键字?
问题描述
'input_folder'
我在一个目录'.dat'
(ABC
MWE如下所示:
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 字符的文件和文件夹?
解决方案
至少有五个问题:
- 处理 Unicode 时,请在任何地方使用它。
os.walk
如果传递 Unicode 路径,将返回 Unicode 文件名。from __future__ import unicode_literals
将默认字符串为 Unicode。 - 打开文件时,关闭它们。稍后重命名时会遇到问题。
result
仍然存在并且引用了最后打开的文件。 - 如评论中所述,在名称之前和之后都使用
os.path.join
theroot
和 thefile
。 os.walk
与topdown=False
. _ 这将首先处理叶节点,因此目录树在遍历它时不会损坏(并且保持有效)root
。dirs
- 首先重命名文件,然后重命名目录,以在遍历目录树时再次不损坏目录树。
结果:
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)
推荐阅读
- go - 用 time.Parse 解析日期
- python - 在python中的撇号之前删除额外的空间
- mule - 基于条件的mule 4中的dataweave2.0转换
- c - 在 C 中,如何使用“make functionName”之类的 makefile 只编译一个函数(需要自定义库中的函数)?
- c - 将文本文件的名称传递给多个函数时的无限循环
- django - custom.methods.wrap 没有返回 HttpResponse 对象。它返回 None 而不是
- arrays - VBA - 来自数组的自定义数字格式 - 特定数组编号后的错误
- node.js - 在 NodeJS 中模拟调用 aws ssm 的最佳方法是什么?
- kotlin - 将 kotlinx.serialization 库与 Bazel 的 rules_kotlin 一起使用
- c++ - 为什么在以下代码中的每个输出后都会得到 32767?