Before this is marked as duplicate please read the full problem.
So I have a folder structure like this:
main.py
|
|_one
|_ one.py
|_ file.txt
What i'm doing is, importing one.py into main.py and calling a function. My py files are,
main.py
import one
one.f1('test')
one.py
def f1(param):
with open("file.txt", "r") as f:
print(f+param)
When I run main.py, I keep getting this error : FileNotFoundError: [Errno 2] No such file or directory: 'file.txt'.
I have also tries os.path.abspath() but still no luck. Am I doing something wrong?
Thank you!
asked Dec 14, 2019 at 4:56
hrishikeshpaul
4691 gold badge11 silver badges29 bronze badges
1 Answer 1
The path is computed from the root directory not the directory the the calling code resides in. Try one/file.txt for Linux environment.
Sign up to request clarification or add additional context in comments.
4 Comments
hrishikeshpaul
Well, that worked, but I'm getting this Pickle error
AttributeError: Can't get attribute 'Node' on <module '__main__' from '/Users/paul-mac/Work/sums/orient.py'>Sab
Post the code , stacktrace and related resources, then the community can help.
ShadowRanger
@hrishikeshpaul: That's an entirely unrelated error, in code you haven't posted. You're welcome to ask a new question with a minimal reproducible example, but asking new questions in comments on the answer to your actual question is frowned upon.
ShadowRanger
Note: I'd suggest not using
one/file.txt since that'll only work if your working directory is the same as main.py's. os.path.join(os.path.dirname(__file__), 'file.txt') (from within one.py) will find the data file relative to the source file, which works regardless of your working directory.lang-py