【问题标题】:Files not being saved in the right directory in Python文件未保存在 Python 的正确目录中
【发布时间】:2021-03-05 20:23:04
【问题描述】:

我有 2 个文件:

  1. 第一个文件test1.py:

    from dir2.test2 import func2
    
    def func1():
       with open("test1.txt", "w") as f:
           f.write("some text")
    
    func1()
    func2()
    
  2. 第二个文件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


【解决方案1】:

像"test1.txt" 这样的相对文件路径是相对于您运行脚本的目录的。因为,您从与自身相同的目录运行 test1.py - 相对路径也被解析到相同的目录。所以test1.txt变成/path/to/dir1/test1.txt

如果您从dir2 中运行test1.py,您会在/path/to/dir2/ 中看到两个文本文件。

这就是相对路径在几乎所有语言中的工作方式。如果您想要可靠的路径构建,请使用os.path 函数

cwd = os.path.dirname(os.path.abspath(__file__))

这将为您提供一个绝对路径您使用它的文件。所以如果你在test1.py 上使用它 - 你会得到/path/to/dir1。现在你可以使用os.path.join 来构建你想要的路径

仅举一个完整的例子,假设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')

【讨论】:

  • 感谢您的详细解释,但我的代码在实现cwd = os.path.dirname(os.path.abspath(__file__)) 后应该是什么样子?
  • 顺便说一下,cwd 代表 当前工作目录 - 这是思考代码在哪里调用以及相对路径指向哪里的有用方法
  • @AbhigyanJaiswal 正如我所说,cwd 是您调用它的文件的路径。您现在可以使用os.path.join(cwd, 'dir2') 获取/path/to/dir1/dir2,您可以在open 中使用它跨度>
  • os.getcwd() 也可以假设代码始终从 test1.py 作为主调用开始。
  • @AbhigyanJaiswal 我明确提到如果__file__ 在test1.py 中解析,你需要加入dir2,但你把它放在test2.py 中。请阅读os.path.dirname 的工作原理 - 如果您在test2.py 上执行os.path.dirname(os.path.abspath(__file__)),它会返回/path/to/dir1/dir2。所以你应该做os.path.join(cwd, 'test2.txt')
猜你喜欢
  • 2021-11-23
  • 2021-12-21
  • 2020-08-08
  • 2020-07-29
  • 1970-01-01
  • 2020-07-31
  • 1970-01-01
  • 1970-01-01
  • 2015-03-12
相关资源
最近更新 更多