0

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

1 Answer 1

0

The path is computed from the root directory not the directory the the calling code resides in. Try one/file.txt for Linux environment.

answered Dec 14, 2019 at 5:01
Sign up to request clarification or add additional context in comments.

4 Comments

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'>
Post the code , stacktrace and related resources, then the community can help.
@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.
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.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.