我有一个名为“test”的主文件夹,内部结构是:
# 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
谢谢
发布于 2017-02-27 08:00:45
发布于 2017-02-27 08:03:30
使用来自环境变量的绝对文件名,或者期望db/目录是当前工作目录的子目录。
这种行为与预期的一样。当前工作目录是您调用代码的位置,而不是代码存储的位置。
folder_test = cwd # assume working directory will have the db/ subdir或folder_test = os.getEnv('TEST_DIR') #使用${TEST_DIR}/db/
https://stackoverflow.com/questions/42480316
复制相似问题