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!

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.

4
  • 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'> Commented Dec 14, 2019 at 5:03
  • Post the code , stacktrace and related resources, then the community can help.
    – Sab
    Commented Dec 14, 2019 at 5:06
  • 1
    @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. Commented Dec 14, 2019 at 5:07
  • 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. Commented Dec 14, 2019 at 5:09

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.