python - 如何在Python中读取unicode文件名?

标签 python windows unicode

我看到了很多关于 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/

相关文章:

python - 使用 Selenium 更改浏览器类型和版本

python - 从嵌套字典中获取值到列表

python - 如何使用 matplotlib 定义图中子图的尺寸(以英寸为单位)?

python - 将目录永久添加到 PYTHONPATH?

c++ - 为什么 InterlockedAdd 在 vs2010 中不可用?

c++ - boost::property_tree::ptree 和带有 BOM 的 UTF-8

python - Pandas:过滤在几个特定列中的任何一个中具有 Null/None/NaN 值的行

c - 有没有办法禁用cmd中的右键菜单?

python - SQLAlchemy 在提交时自动将 str 转换为 unicode

c - 从命令行传递参数时 *argv[] 中的字符大小