【问题标题】:Python: Open function cannot read filePython:打开函数无法读取文件
【发布时间】:2018-11-20 10:10:56
【问题描述】:

我正在使用 python 3.6。我正在尝试读取多个目录中的大量(.txt)文件。有些文件的文件名中有逗号,例如'Proposal for Anne, Barry and Carol.txt'.

以下代码:

for filepath in glob.iglob(params.input_dir + r'\**\**.*', recursive=True):
    # [not shown here: code that filters on .txt filetype]

    with open(filepath) as f:
        for line in f:
            for word in re.findall(r'\w+', line):
                # do stuff

在读取该文件时给我一个错误:

Traceback (most recent call last):
  File "dir_scraper.py", line 50, in <module>
    results_new = scraper.scrape_file(filepath)
  File "C:\Projects\scraper.py", line 33, in scrape_file
    return func(filepath)
  File "C:\Projects\scraper.py", line 15, in txt
   with open(filepath) as f:
FileNotFoundError: [Errno 2] No such file or directory: 'Z:\\groups\\Proposal for Anne, Barry and Carol.txt'

我不想编辑文件的名称。

如何正确读取文件名中带有逗号的文件?

编辑:

  • 我确定路径存在。

  • 解析同一目录中的其他文件没有问题。

  • 尝试直接从命令行打开文件也会给出:系统找不到指定的路径。

  • 另外,我似乎无法重命名文件,如果我尝试通过 Windows 文件资源管理器更改名称以删除逗号(或更改其他内容),则会将其重置为原始文件名。

  • 会不会和文件权限有关?

  • 或者文件名太长了?从Z:[..][..].txt 的完整路径长度为270 个字符。

【问题讨论】:

  • 我无法使用 Python 3.6.3 重现此行为。你能显示变量文件路径的设置位置吗?
  • 也许如果你在目录上使用listdir,你可以看到文件的实际调用。
  • 正确检查文件名,我们通常不需要对文件名或任何参数字符串中的逗号名进行转义/处理。
  • 您确定您的路径Z:\\groups 存在吗?
  • 我确定路径存在。解析同一目录中的其他文件没有问题。直接从命令行,尝试打开文件也会给出:The system cannot find the path specified. 另外,如果我尝试通过 Windows 文件资源管理器更改名称以删除逗号(或更改其他内容),我似乎无法重命名文件,它被重置为原始文件名。

标签: python windows filenames


【解决方案1】:

这在 Python 3、Windows 10 上运行良好

import glob, re
for filepath in glob.iglob('C:/Users/test-ABC/Desktop/test/' + r'\**\**.*', recursive=True):
    with open(filepath) as f:
        print(f)
        for line in f:
            print(line)
            for word in re.findall(r'\w+', line):
                pass

<_io.TextIOWrapper
name='C:/Users/test-ABC/Desktop/test\\loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong
name\\another
looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong
name\\test, file, name.txt' mode='r' encoding='cp1251'>

line1 
line2
line3

可能是漫长道路上的问题。尝试检查这样的问题: Long paths in Python on Windows

【讨论】:

  • Python 3.6+ supports long paths 的清单,所以如果您在 Windows 10 的“HKLM\System\CurrentControlSet\Control\FileSystem”中设置了“LongPathsEnabled”,那么规范化的 DOS 路径支持本机限制最多约 32760 个字符。否则,规范化的 DOS 路径使用 MAX_PATH (260) 个字符的传统限制,较长的路径需要扩展的本地设备路径,其前缀为“\\?\”(或 UNC 的“\\?\UNC\” ) 并且必须是完全限定的(即不是相对的)和 Unicode。
  • 谢谢@eryksun。会注意到这一点。
  • 谢谢!事实证明,这条路确实太长了。逗号把我吓跑了。我将不得不研究如何最好地支持这条漫长的道路。感谢@eryksun 的建议,我看看是否可行。
【解决方案2】:

首先,您只处理文件,而不是目录,其次,您可以在 Windows 上使用 os.path.join 进行转换:

>>>os.path.join("d:\ss")
'd:\\ss'

试试这个:

    from pathlib import Path
    import os
    import re
    pathName='./'# r'd:/xx' on windows
    fnLst=list(filter(lambda x:not x.is_dir(),Path(pathName).glob('**/*.txt')))
    print(fnLst)
    for fn in fnLst:
        with open(fn) as f:
            print()
            print(fn)
            for line in f:
                for word in re.findall(r'\w+', line):
                    print(word,end="|")

输出:

[PosixPath('2.txt'), PosixPath('1.txt')]


2.txt
This|tutorial|introduces|the|reader|informally|to|the|basic|concepts|and|features|of|the|Python|language|and|system|It|helps|to|have|a|Python|interpreter|handy|for|hands|on|experience|but|all|examples|are|self|contained|so|the|tutorial|can|be|read|off|line|as|well|
1.txt
Python|is|an|easy|to|learn|powerful|programming|language|It|has|efficient|high|level|data|structures|and|a|simple|but|effective|approach|to|object|oriented|programming|Python|s|elegant|syntax|and|dynamic|typing|together|with|its|interpreted|nature|make|it|an|ideal|language|for|scripting|and|rapid|application|development|in|many|areas|on|most|platforms|

【讨论】:

    猜你喜欢
    • 2022-08-13
    • 2011-11-19
    • 2016-11-11
    • 2023-01-05
    • 2019-07-11
    • 1970-01-01
    • 1970-01-01
    • 2020-11-17
    • 1970-01-01
    相关资源
    最近更新 更多