【问题标题】:FileNotFoundError with absolute path when trying to read tarball尝试读取压缩包时使用绝对路径的 FileNotFoundError
【发布时间】:2018-11-04 08:42:10
【问题描述】:

我正在尝试从 tar 文件中读取,但尽管指定了绝对路径 我得到一个FileNotFoundError

这是代码的相关部分:

1 from pathlib import Path
2
3 testPath = Path("G:/test.tar")
4 tar = tarfile.open(testPath, "r")
5 ...

并且该文件确实存在。

但我得到的是(来自第 4 行):

FileNotFoundError: [Errno 2] No such file or directory: 'G:\\test.tar'

(顺便说一句,我正在使用 PyCharm。) 我错过了什么?如果需要,我很乐意提供更多信息。

【问题讨论】:

  • 这段代码没有问题。您确定该文件存在并且运行 Python 的用户可以读取该文件吗?
  • 它肯定存在(资源管理器和 PowerShell 以及非零文件大小都可以识别),我正在以管理员身份执行 PyCharm。
  • Ooohhhh 你指引我正确的方向,所以我可以解决这个问题。 Windows 忽略了这是 gzip 压缩的事实,这意味着它实际上是 test.tar.gz。我没有看到,因为在这个特定目录中只有与这个文件分开的文件夹。我刚刚意识到它再次查看了 powershell。感谢您的提示! (我现在觉得有点傻。)

标签: python tarfile


【解决方案1】:

检查以确保您的脚本/文件位于正确的目录中

from pathlib import Path
import tarfile

testPath = Path("Songs.txt.tar")
tar = tarfile.open(testPath, "r")
print(tar) # Returns <tarfile.TarFile object at 0x100d44f98>

print(tarfile.is_tarfile("Songs.txt.tar")) # Returns True if its tar file

【讨论】:

    【解决方案2】:

    由于在第 3 行中,您正在使用以下行生成文件路径:

    testPath = Path("G:/test.tar")
    

    testPath 变量的类型为 pathlib.WindowsPath。 而在下一个 tarfile.open 需要字符串格式的文件路径。

    请尝试以下操作:

    testPath = Path("G:/test.tar")
    tar = tarfile.open(str(testPath), "r")
    

    或:

    testPath = str(Path("G:/test.tar"))
    tar = tarfile.open(testPath, "r")
    

    【讨论】:

    • 这里不需要str()。您可以将Path 传递给open() 就好了。
    • 但是这样做会在执行中报告错误,如果你将它转换为 str 它工作正常。如果不将其转换为 str,可能会失败的原因是什么?
    【解决方案3】:

    解决方案:

    最近一次电脑重置后,我忘记将资源管理器视图再次更改为“始终显示文件类型扩展名”,这导致我没有意识到它应该是

    test.tar.gz
    

    因为除了相关文件之外,此目录中只有其他文件夹。 所以调整我的 testPath 解决了这个问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多