我有2个文件:
第一个档案test1.py
:
from dir2.test2 import func2
def func1():
with open("test1.txt", "w") as f:
f.write("some text")
func1()
func2()
第二档test2.py
:
def func2():
with open("test2.txt", "w") as f:
f.write("some text")
运行之前,我的目录结构如下所示test1.py
:
dir1
|
- test1.py
|
- dir2
|
- test2.py
运行test1.py
目录结构后,如下所示:
dir1
|
- test1.txt
|
- test2.txt
|
- test1.py
|
- dir2
|
- test2.py
但是运行脚本之后,我期望目录结构如下所示:
dir1
|
- test1.txt
|
- test1.py
|
- dir2
|
- test2.txt
|
- test2.py
我尝试搜索解决此问题的方法,但未找到任何解决方法。
所以跑步后还能得到我期望的东西吗test1.py
?
相对文件路径(例如)"test1.txt"
相对于您从中运行脚本的目录。因为,您test1.py
从与其本身相同的目录运行-相对路径也解析到相同的目录。所以test1.txt
变成/path/to/dir1/test1.txt
如果test1.py
从内部运行dir2
,则会在中看到两个文本文件/path/to/dir2/
。
这就是相对路径几乎在每种语言中都起作用的方式。如果您想要可靠的路径构建,请使用os.path
功能
cwd = os.path.dirname(os.path.abspath(__file__))
这将为您提供在上使用此文件的绝对路径。因此,如果您使用此功能test1.py
,您将得到/path/to/dir1
。现在,您可以os.path.join
用来构建所需的路径
仅举一个完整的例子,假设在(即指向)中解析了这一行,则在test2.txt
内部dir2
(位于内部dir1
)进行操作cwd
test1.py
__file__
test1.py
test2_path = os.path.join(cwd, 'dir2', 'test2.txt')
with open(test2_path, 'w') as f:
....
并且,如果cwd
在test2.py
(__file__
指向test2.py的)中得到解决,则可以
test2_path = os.path.join(cwd, 'test2.txt')
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句