Exception has occurred: FileNotFoundError [Errno 2] No such file or directory: 'pi_digits.txt'

143 Views Asked by At

I'm trying to open a file and print out the contents, but when I run the code, I get the error

Exception has occurred: FileNotFoundError
[Errno 2] No such file or directory: 'pi_digits.txt'

Here is the code for the file trying to access the txt file:

"""A simple file reader that accesses the py_digits text file and prints it out."""

# utf-8 is the standard encoding for txt files.
with open('pi_digits.txt', encoding='utf-8') as file_object:
    contents = file_object.read

print(contents)

And it's not a typo:

enter image description here

Thanks for any and all help!

1

There are 1 best solutions below

2
On BEST ANSWER

Your code is correct.

However the environment which calls the code is not.

The output of getcwd() matters a great deal, since you're using a relative pathname. You can print the current working directory as a debugging aid, to better understand what is happening on your system. Consider issuing a chdir to the proper directory, prior to attempting the open.

Alternatively, you might prefer to replace the relative pathname with an absolute pathname:
r"C:\some\where\pi_digits.txt"