【发布时间】:2021-03-05 20:23:04
【问题描述】:
我有 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 之后,有没有得到我所期望的东西。
【问题讨论】:
-
您需要自己处理路径。看stackoverflow.com/questions/32470543/…
-
@chandr3sh 由于我的代码部署在 Heroku 上的不同服务器上,我无法获得完整路径
-
路径都是相对的(根据您的代码),并且取决于您从哪里运行脚本。在 "test2.py" 中,您可能希望将路径指定为
./dir2/test2.txt,因为您正在从dir1中运行脚本 -
当您第一次从 main 运行脚本时,它会将您置于特定位置 - 当前工作目录。您可能会像这样调用 test1.py:
python /home/dev/dir1/test1.py或C:\Users\You\dev\dir1\test1.py。 Python 接收 func2 并读取 open() 调用中相对于当前工作目录 (test1.py) 的相对路径。这就是为什么它将 test2.txt 文件保存在 dir1,而不是 dir2。 -
@PeptideWitch 那么我该如何解决呢?
标签: python python-3.x file directory