Python FileNotFoundError when reading a file in the same directory using pathlib

Question:

Problem:

I’m working through the book “Python Crash Course” by Eric Matthes, and I’ve encountered a problem while trying to read a file named ‘pi_digits.txt’ using Python. Here’s the code I’m using:

from pathlib import Path

# Specify the path to the 'pi_digits.txt' file
path = Path('pi_digits.txt')

# Read and print the contents of the file
contents = path.read_text()
print(contents)

When I run this code, I get an error stating that there’s no such file or directory named ‘pi_digits.txt’. However, I’ve confirmed that the file is in the same directory as my Python script. Here is the error as reference:

Traceback (most recent call last):
  File "c:Usersusernamepython_workfiles_and_exceptionsfile_reader.py", line 8, in <module>
    contents = path.read_text()
  File "C:Program FilesWindowsAppsPythonSoftwareFoundation.Python.3.11_3.11.2032.0_x64__qbz5n2kfra8p0Libpathlib.py", line 1058, in read_text
    with self.open(mode='r', encoding=encoding, errors=errors) as f:
  File "C:Program FilesWindowsAppsPythonSoftwareFoundation.Python.3.11_3.11.2032.0_x64__qbz5n2kfra8p0Libpathlib.py", line 1044, in open
    return io.open(self, mode, buffering, encoding, errors, newline)
FileNotFoundError: [Errno 2] No such file or directory: 'pi_digits.txt'

What I’ve tried:

I’ve also tried specifying the path to the file as files_and_exceptions/pi_digits.txt which works correctly. But according to the book, the original code should work as well.

Here are the troubleshooting steps I’ve taken:

  • Checked that the file is in the same directory as my Python script.
  • Ensured there are no spaces at the start or end of the file name and checked the spelling multiple times.
  • Verified that I have full control over the file’s permissions (I can view, modify, and save the file).

Despite these steps, the issue persists. I’m not sure what else to try and would appreciate any help or suggestions. P.S. I know that files_and_exceptions/pi_digits.txt works correctly, I was just wondering why pi_digits.txt does not work.

Answers:

If you want to read contents in your file using relative path, ensure that the file is located in the same directory as your python script. Then use this:

filename = 'pi_digits.txt'

# Read and print the contents of the file
with open(filename, 'r') as file_object:
    contents = file_object.read()
    print(contents)
Answered By: user16171413

I was getting the same error as you were – what I did to resolve it was close all scripts in VS Studios and exit the program. I then opened VS studio again pressed Ctrl+K+O and selected the folder where my script and txt file are saved.

I ran the code again and boom – I got myself some pi! Here is hoping you figured it out or this works for others who have gotten into the same issue we encountered.

Answered By: BrrIce