Home > OS >  Trying to read an entire file but getting [Errno 2] No such file or directory
Trying to read an entire file but getting [Errno 2] No such file or directory

Time:12-27

I have looked trough many questions regarding this problem, but none seemed to solve my question.

I am currently learning Python and was testing out reading from a file. When I tried to read an entire file like this:

with open('pi_digits.txt') as file_object:
    contents = file_object.read()
print(contents)

Even though I have saved a file called 'pi_digits.txt' in the same directory, an error message pops up, saying: FileNotFoundError: [Errno 2] No such file or directory: 'pi_digits.txt'

The pi_digits.txt file is just a file containing the the first 12 digits of pi. Now my question is: Why does it output an error stating, that pi_digit.txt does not exist?

CodePudding user response:

I recommend adding the following lines before the call to open, to see if the current directory is where you think it is:

import os
print(os.getcwd())

My guess is that statement will print something that you didn't expect (e.g., a directory that doesn't contain a file called pi_digits.txt). If not, then please post the command line you used to call your script, the directory from which the command is run, and we can try to assist further.

  • Related