模块我有一个名为“测试”主文件夹,内部结构为:python3,目录是不正确的,当进口的子文件夹
# folders and files in the main folder 'test'
Desktop\test\use_try.py
Desktop\test\cond\__init__.py # empty file.
Desktop\test\cond\tryme.py
Desktop\test\db\
现在在文件tryme.py。我想产生“DB”
# content in the file of tryme.py
import os
def main():
cwd = os.getcwd() # the directory of the folder 'Desktop\test\cond'
folder_test = cwd[:-4] # -4 since 'cond' has 4 letters
folder_db = folder_test + 'db/' # the directory of folder 'db'
with open(folder_db + 'db01.txt', 'w') as wfile:
wfile.writelines(['This is a test.'])
if __name__ == '__main__':
main()
如果我直接运行这个文件,没有问题,文件“db01.txt”是的“DB”的文件夹中的文件夹中的文件。 但是,如果我运行use_try.py文件,它将无法正常工作。
# content in the file of use_try.py
from cond import tryme
tryme.main()
我得到的错误指的是tryme.py文件。在命令“开放......”
FileNotFoundError: [Error 2] No such file or directory: 'Desktop\db\db01.txt'
好像代码
'os.getcwd()'
仅指调用tryme.py文件中的文件,而不是tryme.py文件本身。
你知道如何解决它,这样我就可以使用文件use_try.py在'db'文件夹中生成'db01.txt'了吗?我使用Python3
感谢
彻底解决了我的问题。谢谢! – aura