Geomatrix Gamer
Geomatrix Gamer

Reputation: 41

Can't open file in the same directory

I was following a python tutorial about files and I couldn't open a text file while in the same directory as the python script. Any reason to this?

f = open("test.txt", "r")

print(f.name)

f.close()

Error message:

Traceback (most recent call last):
  File "c:\Users\07gas\OneDrive\Documents\pyFileTest\ManipulatingFiles.py", line 1, in <module>
    f = open("test.txt", "r")
FileNotFoundError: [Errno 2] No such file or directory: 'test.txt'

Here's a screenshot of proof of it being in the same directory:

Upvotes: 2

Views: 6768

Answers (1)

martineau
martineau

Reputation: 123413

The problem is "test.txt" is a relative file path and will be interpreted relative to whatever the current working directory (CWD) happens to be when the script is run. One simple solution is to use the predefined __file__ module attribute which is the pathname of the currently running script to obtain the (aka "parent") directory the script file is in and use that to obtain an absolute filepath the data file in the same folder.

You should also use the with statement to ensure the file gets closed automatically.

The code below shows how to do both of these things:

from pathlib import Path

filepath = Path(__file__).parent / "test.txt"

with open(filepath, "r") as f:
    print(f.name)

Upvotes: 4

Related Questions