【问题标题】:Cannot open files with accents using Python 2.7 [duplicate]无法使用 Python 2.7 打开带有重音符号的文件 [重复]
【发布时间】:2018-09-03 07:21:40
【问题描述】:

我尝试读取目录中的所有文件,但由于它们包含空格和重音符号,我收到错误(已经阅读了很多关于 SO 的帖子但找不到任何答案)

这会返回一个文件列表

files = [y for x in os.walk(".") for y in glob(os.path.join(x[0], '*.pdf'))]

但是当我尝试一个一个打开它们时

for file in files:
    with open(file,"r") as f:

我收到这类错误(我混淆了字母,因为它是机密的):

IOError: [Errno 22] invalid mode ('r') or filename: '.\abcd?efgh (hijk? lmnop).pdf'

我认为问题是由重音引起的,但由于是 python 给了我文件名,我不明白为什么它们与“open()”不兼容

问候

我该如何解决这个问题?

【问题讨论】:

  • 你试过os.walk(u'.')吗?
  • 你就是那个男人!成功了,非常感谢
  • 你在什么平台上?如果不是 Windows,这可能表明您的文件系统或挂载表存在更深层次的问题,您应该修复这些问题,或者您以后可能会看到其他问题。
  • 另外,你为什么在walk的结果上使用glob?为什么不file for root, dirs, files in os.walk(u'.') for file in files if os.path.splitext(file) == '.pdf'
  • "...由口音引起的" - 我相信他们被称为 diacritics (假设不仅仅是口音给你麻烦)。

标签: python python-2.7 filenames diacritics


【解决方案1】:

我现在这样做:

files = [y for x in os.walk(u'.') for y in glob(os.path.join(x[0], '*.'+extension))]

注意使用u'.' 而不是"."

【讨论】:

  • 你还想要u'*.'。您可能还希望 extension 成为 unicode 而不是 str
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-01
  • 2014-11-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多