user548470 user548470 - 6 months ago 21
Linux Question

Python FileNotFoundError when using open()

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...

Answer

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').

Comments