PS C:\Users\aleks\Desktop\python_work> & C:/Users/aleks/AppData/Local/Programs/Python/Python311/python.exe "c:/Users/aleks/Desktop/python_work/Chapter 10/file_reader.py"
Traceback (most recent call last):
File "c:\Users\aleks\Desktop\python_work\Chapter 10\file_reader.py", line 4, in <module>
contents = path.read_text()
File "C:\Users\aleks\AppData\Local\Programs\Python\Python311\Lib\pathlib.py", line 1058, in read_text
with self.open(mode='r', encoding=encoding, errors=errors) as f:
File "C:\Users\aleks\AppData\Local\Programs\Python\Python311\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'
I have already tried using Bing chatbot to help me find the problem and doing that ruled out the following possibilities:
No spelling mistakes
Code should work
The file_reader.py and pi_digits.txt files are in the same directory
The pi_digits.txt file is not hidden or has restricted access
Currently installed Python version is Python 3.11.2
Updated pip to the latest version 23.0.1 and used the command pip install pathlib to install pathlib should it not be there already
After that Bing ran out of ideas and directed me towards this forum. I hope somebody can help me, since I cannot continue programming if I can’t read files
I tried copying the file into the superordinate folder python_work and now the script works! However, when I type dir, I can see the pi_digits.txt file but not the file_reader.py file which is located in the Chapter_10 folder.
The parent of a process determines its initial working directory. It’s either inherited from the parent’s current working directory or set explicitly by the parent. In this case, the Python process is spawned by PowerShell with the initial working directory “C:\Users\aleks\Desktop\python_work”. In the script, Path('pi_digits.txt') tries to resolve the relative path “py_digits.txt” as a file in the current working directory.
The directory that has the “file_reader.py” script has nothing to do with resolving a relative file path, unless you manually change the current directory to that path, e.g. via os.chdir("C:/Users/aleks/Desktop/python_work/Chapter 10").