简体   繁体   English

从目录内部调用目录外的文件 - Python

[英]Call a file outside of the directory from inside of a directory - Python

I have a directory which has all the files: 我有一个包含所有文件的目录:

myDirectory/
    directory1/
        importantFile.py
    Output.py

How can I import Output.py from importantFile.py without having to put in the same directory? 如何从importantFile.py导入Output.py而不必放在同一目录中?

importantFile.py importantFile.py

import Output
Output.write('This worked!')

Output.py Output.py

class Output():
    def writeOutput(s):
        print s

if "call" is import, in Output.py 如果“call”是导入,则在Output.py中

import sys
import os.path
# change how import path is resolved by adding the subdirectory
sys.path.append(os.path.abspath(os.getcwd()+'/directory1'))
import importantFile

importantFile.f()

sys.path contains the list of path where to look for modules, details in https://docs.python.org/2/library/sys.html sys.path包含查找模块的路径列表,详情参阅https://docs.python.org/2/library/sys.html

The other way is to use the relative notation, for which the python file you want to import should be in a package. 另一种方法是使用相对表示法,您要导入的python文件应该在包中。

You have to make the directory a python package by putting an init .py file. 你必须通过放置一个init .py文件使目录成为一个python包。

Look for the packages section in this link. 在此链接中查找packages部分。

https://docs.python.org/2/tutorial/modules.html https://docs.python.org/2/tutorial/modules.html

import sys
sys.path.append('/full/path/to/use')
global exist_importedname
exist_importedname = True
try:
    import myimport
except ImportError as e:
    exist_importedname = False
    print (e.message)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM