2

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:

19
  • Are you executing it from the same directory? Commented Nov 30, 2021 at 19:51
  • It's telling you that test.txt isn't in the current working directory. We don't know what that is. How are you running the code, and what are the environment options? Commented Nov 30, 2021 at 19:52
  • They are in the same folder check the screen shot Commented Nov 30, 2021 at 19:52
  • How are you running the python script? Commented Nov 30, 2021 at 19:53
  • 1
    I got this error after fixing typo : File "c:\Users\07gas\OneDrive\Documents\pyFileTest\ManipulatingFiles.py", line 3, in <module> f = open(os.path.abspath("test.txt"), "r") FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\07gas\\test.txt' Commented Nov 30, 2021 at 20:00

1 Answer 1

4

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) 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.