Python get module to save to its own folder rather than folder of the file accessing it

StackOverflow https://stackoverflow.com/questions/21570035

  •  07-10-2022
  •  | 
  •  

Question

Right now, I have a module with a file (and class) memoizer.py, called by a file tutorial2.py. Memoizer has a method where it specifies a file name, say "package.txt", and creates that file using open. When I run it, it creates the file in the folder of tutorial2.py. How do I get it to create it in either the folder of memoizer.py, or a subfolder of the folder containing memoizer.py?

Was it helpful?

Solution

Use __file__ module attribute:

import os

with open(os.path.join(os.path.dirname(__file__), 'package.txt'), 'w'):
    pass

According to the documentation:

Modules

...

__file__ is the pathname of the file from which the module was loaded, if it was loaded from a file.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top