Python error: FileNotFoundError: [Errno 2] No such file or directory

前端 未结 2 1072
不思量自难忘°
不思量自难忘° 2021-02-06 13:34

I am trying to open the file from folder and read it but it\'s not locating it. I am using Python3

Here is my code:

import os
import glob

prefix_path          


        
2条回答
  •  温柔的废话
    2021-02-06 14:17

    You are using relative path where you should be using an absolute one. It's a good idea to use os.path to work with file paths. Easy fix for your code is:

    prefix = os.path.abspath(prefix_path) 
    file_list = [os.path.join(prefix, f) for f in os.listdir(prefix) if f.endswith('.txt')]
    

    Note that there are some other issues with your code:

    1. In python you can do for thing in things. You did for thing in range(len(things)) it's much less readable and unnecessary.

    2. You should use context managers when you open a file. Read more here.

提交回复
热议问题