【问题标题】:python - error occurs on relative path but not absolute path in macOSpython - 在相对路径上发生错误,但在 macOS 中不是绝对路径
【发布时间】:2021-06-11 13:09:27
【问题描述】:

我遇到了一个奇怪的问题。我只是想为相对路径做一个基本的显示目录内容。

在桌面上创建了一个测试目录

测试目录内容

test.py
test1 -- folder
    sample.txt

test.py 的内容

import os

dataDir = "test1"
for file in os.listdir("/Users/username/Desktop/test"):
    print(file)

总结 - 绝对路径

  • 作品 - 在 Visual Studio 代码中
  • 作品 - macOS 终端 python3 /Users/username/Desktop/test/test.py

但是当使用变量时我得到一个错误:

test.py 的内容

import os

dataDir = "test1"
for file in os.listdir(dataDir):
    print(file)

摘要 - 相对路径

  • 作品 - 在 Visual Studio 代码中
  • 错误 - macOS 终端 python3 /Users/username/Desktop/test/test.py
回溯(最近一次通话最后): 文件“/Users/username/Desktop/test/test.py”,第 4 行,在 对于 os.listdir(dataDir) 中的文件: FileNotFoundError:[Errno 2] 没有这样的文件或目录:'test1'

【问题讨论】:

  • os.getpwd() 在这两种情况下都给你什么?
  • *os.getcwd() 以上
  • 谢谢@MustafaAydın - 确实

标签: python macos


【解决方案1】:

我完全取决于你启动代码时所在的文件夹。

假设您的 .py 文件位于 folder1/folder2/file.py 中,而您的 test1 文件夹位于 folder1/folder2/test1/... 中。您在文件夹 1 中打开一个终端并启动 python3 /folder2/file.py。程序将检查folder1/test1/ 中的文件。

尝试导航到实际的文件夹,应该可以。如果您想在启动代码的任何地方使用它,您必须对当前目录进行一些检查并手动将代码指向所需的路径。

【讨论】:

    【解决方案2】:

    以下解决方案的灵感来自 answer

    解决问题的一种简单方法是创建绝对路径。 (我建议您在处理不同的目录和文件时始终使用它)

    首先,您需要关心您的实际工作目录。使用 VS Code 时,您的工作目录位于您想要的目录中 (/Users/username/Desktop/test/)。

    但是如果你使用命令行,你的实际工作目录可能会改变,这取决于你从哪里调用脚本。

    要获取脚本实际所在的路径,可以使用python变量__file____file__ 是脚本所在目录的完整路径。

    要正确使用您的脚本并能够使用两种方式调用它,以下实现可以帮助您:

    import os
    
    dataDir = "test1"
    
    # absolute path to the directory where your script is in
    scriptDir = os.path.dirname(__file__)
    
    # combining the path of your script and the 'searching' directory
    absolutePath = os.path.join(scriptDir, dataDir)
    
    for file in os.listdir(absolutePath):
        print(file)
    

    【讨论】:

      猜你喜欢
      • 2015-11-13
      • 1970-01-01
      • 2012-08-24
      • 2011-11-25
      • 2018-06-04
      • 1970-01-01
      • 2016-11-23
      • 2019-09-09
      • 1970-01-01
      相关资源
      最近更新 更多