我看到了很多关于 unicode、utf-8 的论坛,但无法做到这一点。
我使用的是Windows
。
让我们有两个文件夹:
E:\old
---- திருக்குறள்.txt
---- many more unicode named files
E:\new
----
语言:泰米尔语
假设我想将文件移动到 E:\new。我无法正确访问 unicode 文件名。
我尝试过的
import sys
import os
from shutil import copyfile
path = 'E:/old/'
for root, _, files in os.walk(ur''.join(path)):
files = [f for f in files]
copyfile(files[0].encode('utf-8').strip(),'E:/new/') //just for example
错误:
Traceback (most recent call last):
File "new.py", line 8, in <module>
copyfile(files[0].encode('utf-8').strip(),'E:/new/')
File "C:\Python27\lib\shutil.py", line 82, in copyfile
with open(src, 'rb') as fsrc:
IOError: [Errno 2] No such file or directory: '\xe0\xae\xa4\xe0\xae\xbf\xe0\xae\xb0\xe0\xaf\x81\xe0\xae\x95\xe0\xaf\x8d\xe0\xae\x95\xe0\xaf\x81\xe0\xae\xb1\xe0\xae\xb3\xe0\xaf\x8d.txt'
最佳答案
在 Windows 中使用 Unicode 路径。由于您使用的是 os.walk(),您需要正确处理子目录的路径,但您可以只使用 shutil.copytree
代替。如果您不需要子目录,请使用os.listdir
。
这是与os.walk
一起使用的东西:
import os
import shutil
for path,dirs,files in os.walk(u'old'):
for filename in files:
# build the source path
src = os.path.join(path,filename)
# build the destination path relative to the source path
dst = os.path.join('new',os.path.relpath(src,'old'))
try:
# ensure the destination directories and subdirectories exist.
os.makedirs(os.path.dirname(dst))
except FileExistsError:
pass
shutil.copyfile(src,dst)
关于python - 如何在Python中读取unicode文件名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43763796/