简体   繁体   中英

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:

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM