简体   繁体   English

出现错误:FileNotFoundError: [Errno 2] No such file or directory when using Python open()

[英]Getting error: FileNotFoundError: [Errno 2] No such file or directory when using Python open()

I have seen many similar questions to mine, but still I can't resolve the issue.我已经看到了许多与我类似的问题,但我仍然无法解决问题。 I'd be grateful if someone could help.如果有人可以提供帮助,我将不胜感激。 I have a folder with 3.txt files (Text1.txt, Text2.txt, & Text3.txt) in it, plus some other files.我有一个包含 3.txt 文件(Text1.txt、Text2.txt 和 Text3.txt)的文件夹,以及其他一些文件。 I want to read these three files and pass them through a function.我想读取这三个文件并将它们传递给 function。 I wrote a for loop as follows:我写了一个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()

The error message I get is: FileNotFoundError: [Errno 2] No such file or directory: 'Text1.txt'我得到的错误信息是: FileNotFoundError: [Errno 2] No such file or directory: 'Text1.txt'

What am I doing wrong?我究竟做错了什么?

You can use glob , ie:您可以使用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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 收到错误:FileNotFoundError:[Errno 2]没有这样的文件或目录:试图打开文件时 - Getting a error: FileNotFoundError: [Errno 2] No such file or directory: while trying to open a file Python错误:FileNotFoundError:[Errno 2]没有这样的文件或目录(read_csv打开) - Python error: FileNotFoundError: [Errno 2] No such file or directory(read_csv with open) python 打开错误返回“FileNotFoundError: [Errno 2] No such file or directory:” - python open error return"FileNotFoundError: [Errno 2] No such file or directory: " Python 错误 FileNotFoundError: [Errno 2] 没有这样的文件或目录 - Python Error FileNotFoundError: [Errno 2] No such file or directory FileNotFoundError: [Errno 2] 没有这样的文件或目录 Azure Python 错误 - FileNotFoundError: [Errno 2] No such file or directory Azure Python error Python 错误:FileNotFoundError: [Errno 2] 没有那个文件或目录 - Python error: FileNotFoundError: [Errno 2] No such file or directory Python 错误 FileNotFoundError: [Errno 2] 没有这样的文件或目录: - Python error FileNotFoundError: [Errno 2] No such file or directory: FileNotFoundError: [Errno 2] 没有这样的文件或目录(python 错误) - FileNotFoundError: [Errno 2] No such file or directory (python error) Python: FileNotFoundError: [Errno 2] No such file or directory 错误 - Python: FileNotFoundError: [Errno 2] No such file or directory error 打开 FileNotFoundError: [Errno 2] 没有这样的文件或目录: - with open FileNotFoundError: [Errno 2] No such file or directory:
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM