1

I'm using with open('myFile', 'rb') as file: to read a file. When running the program with python myProgram.py everything works fine. But as soon I try to run it without cd-ing into the directory of myProgram.py and use an absolute path instead (like python /home/myName/myCode/myProgram.py I always get this error message: FileNotFoundError: [Errno 2] No such file or directory.

So why does open() behave differently depending on how the Python program is started? And is there a way to make things work even if starting with an absolute path?

I've already tried open('/home/myName/myCode/myfile', 'rb') but without success...

5
  • Are you sure the file is where you think it is? Commented May 25, 2016 at 17:52
  • 1
    run 'pwd' in the directory where you are able to run the program. post results. Commented May 25, 2016 at 17:53
  • you should provide your full traceback as well Commented May 25, 2016 at 18:10
  • The file is in the same directory as the python program. WHen I runpwd in the directory where the program works it returns /home/myName/myCode. So that's exactly the directory where both my program and the file are. Commented May 25, 2016 at 18:13
  • The current working directory of a process and the directory that contains the script are not necessarily the same thing. Commented May 25, 2016 at 18:25

2 Answers 2

4

So why does open() behave differently depending on how the Python program is started? And is there a way to make things work even if starting with an absolute path?

Because that is standard behavior. Not just for Python, but for all applications (at least all that I know of). A relative path (like 'myfile') is assumed to be in the current directory. That path will change depending on what directory you are sitting in when you launch the script from a shell. If you don't give an absolute path, how would Python know which file to use in a directory structure like this?

root
|-- dir1
|   `-- myFile
`-- dir2
    `-- myFile

You were on the right track with open('/home/myName/myCode/myfile', 'rb').

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, this completely makes sense. I tried again with open('/home/myName/myCode/myfile', 'rb') and now it's working!
1

Let's say you run pwd and it returns /home/myName. If you then run /home/myName/code/myProgram.py, the working directory of your program is not /home/myName/code; it's /home/myName. The working directory of a process in inherited from the parent process, not set based on where the script is located.

Comments

Your Answer

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.