【发布时间】:2017-10-01 12:09:27
【问题描述】:
我看到很多关于 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'
【问题讨论】:
-
我相信你只需要将路径作为 unicode-string 传递(更改为
path = u'E:\old')......我不久前遇到了同样的问题,我认为这解决了它。 (我现在不在 Windows 机器上,无法验证) -
但由于某些原因,我想一个一个地读取文件。 :(
-
您不需要
.encode('utf-8').strip(),只需使用files[0],但是您确实需要添加os.path.join()来构建文件的完整路径,这应该传递给copyfile()。 -
绝对不编码。使用 Windows 路径时,始终使用 Unicode。 Python 2 在这里并不完美,但
os模块几乎总是使用 [W]ide-character Windows API 来处理 Unicode 参数。