Python:TarFile.open没有这样的文件或目录

Python:TarFile.open没有这样的文件或目录,python,cygwin,Python,Cygwin,因此,我对python相当陌生,我正在编写一个脚本,该脚本需要解压一个文件。我使用这个简单的函数 def untar(source_filename, dest_dir): for f in os.listdir(): print(f) if(source_filename.endswith("tar.gz") or source_filename.endswith(".tar")): tar = tarfile.open(source_file

因此,我对python相当陌生,我正在编写一个脚本,该脚本需要解压一个文件。我使用这个简单的函数

def untar(source_filename, dest_dir):
    for f in os.listdir():
        print(f)

    if(source_filename.endswith("tar.gz") or source_filename.endswith(".tar")):
        tar = tarfile.open(source_filename)
        tar.extractall(dest_dir)
        tar.close()
    else:
        raise Exception("Could not retrieve .depends for that file.")
为了调试的目的,我添加了for循环的首字母。当我调用它时,它会在当前工作目录中打印出我需要的文件名,这意味着它确实存在。这是全部输出

 dep.tar.gz
Traceback (most recent call last):
  File "init.py", line 70, in <module>
    untar('dep.tar.gz', ".")
  File "init.py", line 17, in untar
    tar = tarfile.open(source_filename)
  File "/usr/lib/python3.4/tarfile.py", line 1548, in open
    return func(name, "r", fileobj, **kwargs)
  File "/usr/lib/python3.4/tarfile.py", line 1646, in bz2open
    compresslevel=compresslevel)
  File "/usr/lib/python3.4/bz2.py", line 102, in __init__
    self._fp = _builtin_open(filename, mode)
FileNotFoundError: [Errno 2] No such file or directory: 'dep.tar.gz'
dep.tar.gz
回溯(最近一次呼叫最后一次):
文件“init.py”,第70行,在
untar(‘副焦油’gz’,“)
untar中第17行“init.py”文件
tar=tarfile.open(源文件名)
文件“/usr/lib/python3.4/tarfile.py”,第1548行,打开
返回函数(名称,“r”,文件对象,**kwargs)
bz2open中的文件“/usr/lib/python3.4/tarfile.py”,第1646行
压缩级别=压缩级别)
文件“/usr/lib/python3.4/bz2.py”,第102行,在__
self.\u fp=\u内置\u打开(文件名,模式)
FileNotFoundError:[Errno 2]没有这样的文件或目录:“dep.tar.gz”

有人能告诉我,它是如何看到工作目录中的文件,然后突然无法看到工作目录中的文件的吗?

我用来创建tar的程序在文件名的开头放了一个空格。因此python正在寻找'dep.tar.gz',实际的文件名是'dep.tar.gz'。泰本


TIL-文件名可以以空格开头。

您尝试过dep.tar.gz文件的绝对路径吗?如何将dep.tar.gz文件名源文件名传递给函数?调用在输出中。untar('dep.tar.gz',“)我将尝试使用绝对路径文件的绝对路径也不起作用。文件名开头是否有空格?不太可能,但是输出中有一个空格。你的脚本在Mac上对我来说非常适合。dep.tar.gz文件是否与init.py文件位于同一目录中?