2017-02-27 27 views
0

模块我有一个名为“测试”主文件夹,内部结构为: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

感谢

回答

2

好像你需要的是working directory,但tryme.py文件的目录。从一个环境变量

curdir = os.path.dirname(__file__) 
+1

彻底解决了我的问题。谢谢! – aura

0

使用绝对的文件名,或者预计DB /目录设置为当前工作目录的子目录:

这可以使用魔法__file__来解决。

此行为与预期的相同。当前工作目录是您调用代码的位置,而不是代码的存储位置。

folder_test = cwd # assume working directory will have the db/ subdir 

或 folder_test = os.getEnv( 'TEST_DIR')#使用$ {} TEST_DIR/DB/

相关问题