Reputation: 5074
I have a package that looks like the following
package/
__init__.py
module.py
In module.py
I have something like this
def function(file_name):
with open(file_name) as f:
# do stuff
Somewhere else in an arbitrary directory I have a python file that looks something like this
import package
package.function("some_file.txt")
But upon running it, it's giving me FileNotFoundError: [Errno 2] No such file or directory: "some_file.txt"
.
The problem is that the absolute path of some_file.txt
may look something like C:\Users\USER\Documents\some_file.txt
, but in package.function
the path absolute path is something like C:\Users\USER\Documents\package\some_file.txt
. Is there any way I can make it so that calling package.function
from some file outside the package
directory automatically includes the absolute path of the file I want to open?
Sorry if my terminology is really ambiguous, I'm really unfamiliar with os
stuff.
Edit: The exact file setup I have looks like this:
directory/
foo.py
package/
__init__.py
module.py
another_directory/
bar.txt
And foo.py
looks exactly like this
import package
package.function("another_directory/bar.txt")
Upvotes: 0
Views: 125
Reputation: 36346
I think you're missing the point.
It's not important where the source code lies, relative paths (and pure file names are relative paths) are always interpreted relative to the directory that the program process runs in (ie. the directory you are when you type python C:\Path\to\my\python\code\code.py
)
Upvotes: 1