简体   繁体   中英

FileNotFound Error: [Errno 2] No such file or directory b when iterating through list of files in Python on Windows?

I am getting a FileNotFound error when iterating through a list of files in Python on Windows.

The specific error I get looks like:

FileNotFoundError: File b'fileName.csv' does not exist

In my code, I first ask for input on where the file is located and generate a list using os (though I also tried glob ):

directory = input('In what directory are your files located?')
fileList = [s for s in os.listdir(directory) if s.endswith('.csv')]

When I print the list, it does not contain byte b before any strings, as expected (but I still checked). My code seems to break at this step, which generates the error:

for file in fileList:
    pd.read_csv(file)  # breaks at this line

I have tried everything I could find on Stack Overflow to solve this problem. That includes:

  • Putting an r or b or rb right before the path string
  • Using both the relative and absolute file paths
  • Trying different variations of path separators ( / , \\ , \\\\ , etc.)

I've been dealing with Windows-related issues lately (since I normally work in Mac or Linux) so that was my first suspicion. I'd love another set of eyes to help me figure out where the snag is.

A2A.

Although the list was generated correctly because the full directory path was used, the working directory when the file was being run was . . You can verify this by running os.getcwd() . When later iterating through the list of file names, the program could not find those file names in the . directory, as it shouldn't. That list is just a list of file names; there was no directory tied to it so it used the current directory.

The easiest fix here is to change the directory the file is running through after the input. So,

directory = input('In what directory are your files located?')
os.chdir(directory)  # Points os to given directory to avoid byte issue

If you need to access multiple directories, you could either do this right before you switch to each directory or save the full file path into your list instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM