【问题标题】:How to read unicode filename in python?如何在python中读取unicode文件名?
【发布时间】: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 参数。

标签: python windows unicode


【解决方案1】:

在 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)

【讨论】:

    猜你喜欢
    • 2013-06-30
    • 1970-01-01
    • 2013-08-08
    • 2018-03-25
    • 1970-01-01
    • 1970-01-01
    • 2016-11-15
    • 2023-03-20
    • 2015-07-31
    相关资源
    最近更新 更多