Issue
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:
- 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.
Solution
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 - journpy
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.