Character encoding 用python在目录中列出中文文件名
我试图列出一个目录中所有文件的名称和大小,但当有中文文件时出现错误,我在Windows7上使用的是Python2.7 这是我的密码Character encoding 用python在目录中列出中文文件名,character-encoding,python-2.7,Character Encoding,Python 2.7,我试图列出一个目录中所有文件的名称和大小,但当有中文文件时出现错误,我在Windows7上使用的是Python2.7 这是我的密码 import os path = '\' listing = os.listdir(path) for infile in listing: if infile.endswith(".csv"): print infile + ";"+ str(os.path.getsize(path + infile)) 这就是我得到的错误 Trace
import os
path = '\'
listing = os.listdir(path)
for infile in listing:
if infile.endswith(".csv"):
print infile + ";"+ str(os.path.getsize(path + infile))
这就是我得到的错误
Traceback (most recent call last):
File "file_size.py", line 8, in <module>
print infile + ";"+ str(os.path.getsize(path + infile))
File "C:\Python27\lib\genericpath.py", line 49, in getsize
return os.stat(filename).st_size
WindowsError: [Error 123] The filename, directory name, or volume label syntax is incorrect: '\DB?1333366331.436754.048342.csv'
C:\>python file_size.py
File "file_size.py", line 7
if infile.endswith(".csv"):
^
IndentationError: unindent does not match any outer indentation level
回溯(最近一次呼叫最后一次):
文件“File_size.py”,第8行,在
打印infle+“;”+str(os.path.getsize(path+infle))
文件“C:\Python27\lib\genericpath.py”,第49行,在getsize中
返回os.stat(文件名).st\u大小
WindowsError:[错误123]文件名、目录名或卷标语法不正确:'\DB?133366331.436754.048342.csv'
C:\>python文件\u size.py
文件“File_size.py”,第7行
如果填充.endswith(“.csv”):
^
缩进错误:未缩进与任何外部缩进级别不匹配
导致错误的文件名为DB表133366331.436754.048342.csv
我怎样才能避免这个问题
提前谢谢我会尝试将您的根路径设置为unicode。我猜listdir使用与初始字符串相同的编码,并且在读取非ascii字符时出错 i、 e 资料来源:
“在2.3版中更改:在Windows NT/2k/XP和Unix上,如果路径是Unicode对象,则结果将是Unicode对象列表。不可编辑的文件名仍将作为字符串对象返回。”谢谢,这正是我所需要的。我添加了infieutf=infie.encode(“utf-8”),现在可以工作了
path = u'\'