【问题标题】:Getting error: FileNotFoundError: [Errno 2] No such file or directory when using Python open()出现错误:FileNotFoundError: [Errno 2] 使用 Python open() 时没有这样的文件或目录
【发布时间】:2020-04-19 22:28:01
【问题描述】:

我已经看到了许多与我类似的问题,但我仍然无法解决问题。如果有人可以提供帮助,我将不胜感激。 我有一个包含 3 个 .txt 文件(Text1.txt、Text2.txt 和 Text3.txt)的文件夹,以及一些其他文件。我想读取这三个文件并将它们传递给一个函数。我写了一个for循环如下:

file_list = [f for f in listdir("Path_to_my_files") if 
isfile(join("Path_to_my_files",f))]

def Read (files):
    for f in files:
      if f.endswith (".txt"):
        data = open(r'Path_to_my_files/f')
        text = data.read()

我得到的错误信息是: FileNotFoundError: [Errno 2] 没有这样的文件或目录:'Text1.txt'

我做错了什么?

【问题讨论】:

  • data = open(r'Path_to_my_files/' + f ) ?
  • also : with open(filename) as f: 建议使用上下文

标签: python path load file-not-found listdir


【解决方案1】:

你可以使用glob,即:

from glob import glob

p = "/path/to/*.txt"
for t in glob(p):
    with open(t) as f:
        text = f.read()
    # do something with text

【讨论】:

    猜你喜欢
    • 2018-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-12
    • 1970-01-01
    • 1970-01-01
    • 2022-12-13
    • 2020-06-28
    相关资源
    最近更新 更多