Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/347.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用sys.path.append在python中导入文件?_Python_Python 2.7_Relative Path_Filepath_Sys - Fatal编程技术网

如何使用sys.path.append在python中导入文件?

如何使用sys.path.append在python中导入文件?,python,python-2.7,relative-path,filepath,sys,Python,Python 2.7,Relative Path,Filepath,Sys,我的桌面上有两个目录,DIR1和DIR2,其中包含以下文件: DIR1: file1.py DIR2: file2.py myfile.txt 这些文件包含以下内容: file1.py file2.py myfile.txt 现在,有两种情况。第一个有效,第二个错误 情景1 我将cd放入DIR2并运行file2.py,它运行起来没有问题 情景2 我将cd放入DIR1并运行file1.py,它会抛出一个错误: Traceback (most recent call last): File

我的桌面上有两个目录,
DIR1
DIR2
,其中包含以下文件:

DIR1:
file1.py

DIR2:
file2.py  myfile.txt
这些文件包含以下内容:

file1.py file2.py myfile.txt 现在,有两种情况。第一个有效,第二个错误

情景1 我将
cd
放入
DIR2
并运行
file2.py
,它运行起来没有问题

情景2 我将
cd
放入
DIR1
并运行
file1.py
,它会抛出一个错误:

Traceback (most recent call last):
  File "<absolute-path>/DIR1/file1.py", line 6, in <module>
    import file2
  File "../DIR2/file2.py", line 9, in <module>
    myfile = open(MY_FILE)
IOError: [Errno 2] No such file or directory: 'myfile.txt'
回溯(最近一次呼叫最后一次):
文件“/DIR1/file1.py”,第6行,在
导入文件2
文件“./DIR2/file2.py”,第9行,在
myfile=打开(MY_文件)
IOError:[Errno 2]没有这样的文件或目录:“myfile.txt”
但是,这对我来说毫无意义,因为我已经使用命令
sys.path.append('../DIR2')
将路径追加到
file1.py


file1.py
file2.py
myfile.txt
在同一目录下,但它抛出了一个错误时,为什么会发生这种情况?多谢各位

您可以使用模块的
\uuuu file\uuu
属性创建相对于模块的路径。例如:

myfile = open(os.path.join(
    os.path.dirname(__file__),
    MY_FILE))
无论从何处开始脚本,都可以执行您想要的操作。

替换

MY_FILE = "myfile.txt"
myfile = open(MY_FILE) 

这就是你的问题所提到的相对路径解决方案。这假设您是从myfile.txt的dir-one运行它。。。所以并不理想

如果您知道my_file.txt总是与file2.py位于同一目录中,那么您可以在file2中尝试类似的内容

from os import path

fname =  path.abspath(path.join(path.dirname(__file__), "my_file.txt"))
myfile = open(fname)

Python的
sys.path
只影响Python查找模块的方式。如果要
打开
文件,则不涉及
sys.path
。您的
打开
失败,因为您没有从包含
myfile.txt
的目录运行脚本。好的,谢谢@larsks。但是,我如何影响python打开文件的方式?i、 e.如何允许它从其他目录打开文件?@Hunle使用该文件的完整相对路径,或尽可能使用绝对路径。不能使用绝对路径。这是一个共享应用程序。好的,谢谢。你从来没有告诉我们你是如何运行这些文件的。如果在运行
file2
之前更改为
DIR2
,这将解释您看到的行为。如果您正在执行其他操作,请向我们展示确切的步骤。我可以建议您在每个文件中放入一个print(\uuuu file\uuuu+“”+os.getcwd())调用吗。。我想您可能对路径的解析方式理解不透彻。首先,我会打印出路径的值(
thepath=os.path.join(os.path.dirname(+'/../',JSON_文件)
),看看它是否正常。我怀疑我们正在处理一个问题,因为你的问题不清楚你为什么要访问这样的文件。我知道了。谢谢你的帮助。
myfile = open(os.path.join(
    os.path.dirname(__file__),
    MY_FILE))
MY_FILE = "myfile.txt"
myfile = open(MY_FILE) 
MY_FILE = os.path.join("DIR2", "myfile.txt")
myfile = open(MY_FILE) 
from os import path

fname =  path.abspath(path.join(path.dirname(__file__), "my_file.txt"))
myfile = open(fname)