pythonpython-3.xfile-iopathlibfilenotfounderror

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


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:\Users\username\python_work\files_and_exceptions\file_reader.py", line 8, in <module>
    contents = path.read_text()
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.11_3.11.2032.0_x64__qbz5n2kfra8p0\Lib\pathlib.py", line 1058, in read_text
    with self.open(mode='r', encoding=encoding, errors=errors) as f:
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.11_3.11.2032.0_x64__qbz5n2kfra8p0\Lib\pathlib.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:

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.


Solution

  • 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.