【问题标题】:How to read japanese filename file correctly by python in windows如何在windows中通过python正确读取日文文件名文件
【发布时间】:2014-02-27 03:07:55
【问题描述】:
import os

path="."
dirList=os.listdir(path)

for fileName in dirList:
    print fileName

如果文件名是japanese,打印到控制台将不正确(如?????.csv,????abc.csv)

open('XXX.csv').readlines()

如果文件名是日语, IOError:没有这样的文件或目录:\xe4\xb8\xbcABC.csv

【问题讨论】:

  • python2 库在 unicode 支持方面很糟糕,一些库具有向后兼容的“解决方法”,但其他一些库(如子进程)没有。
  • fileName = fileName.decode("UTF-8")(from jmunsch's link) 还是 IOError,把文件名改成英文就可以了
  • fileName2 = fileName.decode("UTF-8") open('fileName2').readlines() 它可以工作。但是文件名必须是日文字符串,我无法得到正确的文件名(成为?? ?.csv) by os.listdir(),必须硬编码fileName。这个问题可以概括为“how to get correct Japanese fileName by os.listdir()”

标签: python encoding character-encoding


【解决方案1】:

所有问题都解决了,谢谢

1)如果你想通过os.listdir正确获取不是英文的文件名(如日文、中文)(不是???.csv) 您可以在路径字符串之前添加 u listdir doesn't print non-english letters correctly

2)如果要打开文件,可以使用file.decode('UTF-8')

#-*- coding: utf-8 -*-
import os

dirList=os.listdir(u"C:\\")

for file in dirList:
    print file
    file2 = file.decode('UTF-8')
    count = len(open('C:\\' + file2).readlines())
    print count 

【讨论】:

    猜你喜欢
    • 2013-03-08
    • 1970-01-01
    • 2018-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-15
    • 2017-10-26
    • 1970-01-01
    相关资源
    最近更新 更多