现在,我有一个带有文件(和类)memoizer.py 的模块,由文件 tutorial2.py 调用。 Memoizer 有一个方法,它指定一个文件名,比如“package.txt”,并使用 open 创建该文件。当我运行它时,它会在 tutorial2.py 的文件夹中创建文件。如何在 memoizer.py 文件夹或包含 memoizer.py 的文件夹的子文件夹中创建它?
请您参考如下方法:
使用__file__模块属性:
import os
with open(os.path.join(os.path.dirname(__file__), 'package.txt'), 'w'):
pass
根据 the documentation :
Modules
...
__file__is the pathname of the file from which the module was loaded, if it was loaded from a file.
