1

I'm trying to use a program to read from a file with pi-digits. The program and the text file with the pi-digits are in the same directory, but i still get the error message :

with open('pi_digits.txt') as file_object:
    contents = file_object.read()
print(contents.rstrip())

Traceback (most recent call last):
  File "C:\Python\Python_Work\python_crash_course\files_and_exceptions\file_reader.py", line 1, in <module>
    with open('pi_digits.txt') as file_object:
FileNotFoundError: [Errno 2] No such file or directory: 'pi_digits.txt'

I have looked for a solution but haven't found any.

I found a piece of code which supposedly shows me what the working directory is. I get an output that shows a directory that is 2 steps above the directory i have my programs and text file inside.

import os

cwd = os.getcwd()  # Get the current working directory (cwd)
files = os.listdir(cwd)  # Get all the files in that directory
print("Files in %r: %s" % (cwd, files))

So when i put the pi text document in the directory that the output is showing (>python_work), the program is working. When it does not work is when the text file is in ">files_and_exceptions" which is the same file the program itself is inside. My directory looks like this when it is not working:

>python_work
   >python_crash_course
      >files_and_exceptions
          file_reader.py
          pi_digits.txt
          show_working_directory.py

And like this when it is working:

>python_work
    pi_digits.txt
   >python_crash_course
      >files_and_exceptions
          file_reader.py
          show_working_directory.py

I'm new to python and really appreciate any help.

Thanks!

Theo Belin
  • 11
  • 1
  • 1
    Start your script from the directory that contains your `pi_digits.txt` file. Or give the complete path as filename: `with open(r'C:\Python\Python_Work\python_crash_course\files_and_exceptions\pi_digits.txt'):`. If you don't give the full path, Python expects your file to be in your current working directory, which is the one in which you were when launching the script. – Thierry Lathuille Dec 06 '20 at 08:06
  • Read this for more information on how things work in Python: https://stackoverflow.com/questions/5137497/find-current-directory-and-files-directory – David Brabant Dec 06 '20 at 08:12
  • That is what i do, i start my script from the directory that contains my pi_digits.txt. – Theo Belin Dec 06 '20 at 08:25

1 Answers1

0

Relative path (one not starting with a leading /) is relative to some directory. In this case (and generally*), it's relative to the current working directory of the process.

In your case, given the information you've provided, for it would be "python_crash_course/files_and_exceptions/pi_digits.txt" in the first case as you appear to be running the script from python_work directory.

If you know the file to be in the same directory as the script itself, you could also say:

import os.path
...
os.path.join(os.path.dirname(__file__), "pi_digits.txt")

instead of "pi_digits.txt". Or the same using pathlib:

from pathlib import Path
...
Path(__file__).with_name("pi_digits.txt")

Actually unless you have a point to anchor to like the script itself, using relative filename / path (using absolute paths brings its own problems too) in the code directly is rather fragile and in that case getting it as a parameter of a function (and ultimately argument of CLI or script call in general) or alternatively reading it from standard input would be more robust.


* I would not make that an absolute statement, because there are situations and functions that can explicitly provide different anchor point (e.g. os.path.relpath or openat(2); or as another example a symlink target)

Ondrej K.
  • 8,841
  • 11
  • 24
  • 39
  • Thanks for the answer. As I understand your answer, I should be able to use the default standard path (both the file and script is in the same folder, and giving the arg as the file name) when both the file and script is in the same folder. The thing is, they both are in the same folder but i still get an error message. – Theo Belin Dec 06 '20 at 11:33
  • I am not sure I fully follow the recap, but I don't think that is what I've said. If you have both `pi_digits.txt` and the script in the same location, you could use either snippet to give path relative to the script (`__file__`, which itself will resolve to a correct absolute path). Since you really should have some fixed point, if that was not an option, file name should be a runtime parameter; or other means of obtaining content should be considered, e.g. reading from stdin).. – Ondrej K. Dec 06 '20 at 18:13
  • That was not really my question. My question was about why this specific scenario does not work. In my python education book, this is given as an example, so i expected it to work but it does not. I understand that there are other ways of providing a path, my question is only about why just this does not work. – Theo Belin Dec 07 '20 at 17:21
  • The short version is: because you are in a different directory when calling the script than the book has expected. From where you appear to have originally started, do `cd python_crash_course/files_and_exceptions` before calling the script from the same shell. – Ondrej K. Dec 07 '20 at 18:58
  • Thanks for the answer. As I have understood it, both from my book, and from other sources, this scenario should work as long as both the script and the text file is in the same directory. I guess my question is why it does not work for me, what I have done wrong compared to the book. I understand if you can't help me in this regard. – Theo Belin Dec 08 '20 at 09:30