繁体   English   中英

在Windows上的Python 3.4中处理Unicode文件名

[英]handling Unicode filenames in Python 3.4 on Windows

我试图找到一种可靠的方法来在Windows中使用Python扫描文件,同时考虑到文件名中可能存在各种Unicode代码点的可能性。 我已经看到了几个针对此问题的建议解决方案,但是它们都无法解决我在扫描由实际软件和用户创建的文件名时遇到的所有实际问题。

下面的代码示例是尝试解脱并演示核心问题。 它在子文件夹中用我遇到的各种变化创建了三个文件,然后尝试浏览该文件夹并显示每个文件名以及文件内容。 尝试读取第三个测试文件时,它将崩溃,并带有OSError [Errno 22] Invalid参数。

import os

# create files in .\temp that demonstrate various issues encountered in the wild
tempfolder = os.getcwd() + '\\temp'
if not os.path.exists(tempfolder):
    os.makedirs(tempfolder)
print('file contents', file=open('temp/simple.txt','w'))
print('file contents', file=open('temp/with a ® symbol.txt','w'))
print('file contents', file=open('temp/with these chars ΣΑΠΦΩ.txt','w'))

# goal is to scan the files in a manner that allows for printing
# the filename as well as opening/reading the file ...
for root,dirs,files in os.walk(tempfolder.encode('UTF-8')):
    for filename in files:
        fullname = os.path.join(tempfolder.encode('UTF-8'), filename)
        print(fullname)
        print(open(fullname,'r').read())

如代码中所说,我只希望能够显示文件名并打开/读取文件。 关于文件名的显示,我不在乎特殊情况下Unicode字符是否正确呈现。 我只想以一种唯一标识正在处理的文件的方式打印文件名,并且不会因这些异常的文件名而引发错误。

如果注释掉最后一行代码,则此处显示的方法将显示所有三个文件名而不会出现错误。 但是,它不会以其他Unicode名称打开文件。

有没有一种方法可以在Python中可靠地显示/打开所有这三种文件名变体? 我希望在那里,而我对Unicode微妙之处的有限了解使我无法看到它。

下面的工作正常, 如果你保存在声明编码的文件, 如果您使用支持正在显示的字符的IDE或终端编码。 请注意,这不必是UTF-8。 文件顶部的声明仅是源文件的编码。

#coding:utf8
import os

# create files in .\temp that demonstrate various issues encountered in the wild
tempfolder = os.path.join(os.getcwd(),'temp')
if not os.path.exists(tempfolder):
    os.makedirs(tempfolder)
print('file contents', file=open('temp/simple.txt','w'))
print('file contents', file=open('temp/with a ® symbol.txt','w'))
print('file contents', file=open('temp/with these chars ΣΑΠΦΩ.txt','w'))

# goal is to scan the files in a manner that allows for printing
# the filename as well as opening/reading the file ...
for root,dirs,files in os.walk(tempfolder):
    for filename in files:
        fullname = os.path.join(tempfolder, filename)
        print(fullname)
        print(open(fullname,'r').read())

输出:

c:\\temp\simple.txt
file contents

c:\temp\with a ® symbol.txt
file contents

c:\temp\with these chars ΣΑΠΦΩ.txt
file contents

如果您使用的终端不支持对文件名中使用的字符进行编码,则会得到UnicodeEncodeError 更改:

print(fullname)

至:

print(ascii(fullname))

并且您会看到文件名已正确读取,但是无法在终端编码中打印一个或多个符号:

'C:\\temp\\simple.txt'
file contents

'C:\\temp\\with a \xae symbol.txt'
file contents

'C:\\temp\\with these chars \u03a3\u0391\u03a0\u03a6\u03a9.txt'
file contents

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM