【问题标题】:Untar file in Python script with wildcard使用通配符在 Python 脚本中解压缩文件
【发布时间】:2016-08-22 15:30:27
【问题描述】:

我正在尝试使用 Python 脚本从 HDFS 导入 tar.gz 文件,然后解压缩它。文件如下20160822073413-EoRcGvXMDIB5SVenEyD4pOEADPVPhPsg.tar.gz,结构相同。

在我的 python 脚本中,我想将它复制到本地并提取文件。我正在使用以下命令来执行此操作:

import subprocess
import os
import datetime
import time

today = time.strftime("%Y%m%d")

#Copy tar file from HDFS to local server
args = ["hadoop","fs","-copyToLocal", "/locationfile/" + today + "*"]

p=subprocess.Popen(args)

p.wait()

#Untar the CSV file 
args = ["tar","-xzvf",today + "*"]

p=subprocess.Popen(args)

p.wait()

导入工作完美,但我无法提取文件,我收到以下错误:

['tar', '-xzvf', '20160822*.tar']
tar (child): 20160822*.tar: Cannot open: No such file or directory
tar (child): Error is not recoverable: exiting now
tar: Child returned status 2
tar: Error is not recoverable: exiting now
put: `reportResults.csv': No such file or directory

谁能帮帮我?

非常感谢!

【问题讨论】:

    标签: python unix rar


    【解决方案1】:

    尝试使用shell 选项:

    p=subprocess.Popen(args, shell=True)
    

    来自the docs

    如果shell为True,指定的命令将通过 贝壳。如果您主要将 Python 用于 它在大多数系统外壳上提供的增强控制流,并且仍然需要 方便访问其他外壳功能,例如外壳管道, 文件名通配符、环境变量扩展、~的扩展 到用户的主目录。

    注意:

    但是,请注意 Python 本身提供了许多实现 类似 shell 的功能(特别是 glob、fnmatch、os.walk()、 os.path.expandvars()、os.path.expanduser() 和 shutil)。

    【讨论】:

    • 您好,谢谢。我现在有一个不同的错误:tar:您必须指定-Acdtrux' or --test-label' 选项之一尝试tar --help' or tar --usage' 以获取更多信息。谢谢
    • @Majid 将 today 变量传递给 Popen 时有什么内容?
    • 这是一天中的日期,格式为 20160822。我这样做是因为我每天收到一个文件,并且我尝试自动化该过程
    • 在将args 传递给Popen 之前尝试打印它,这样您就可以在终端中使用相同的值进行测试。原来的问题解决了,以后都在shell端了。
    • 打印给了我 ['tar', 'xvf', '20160822*'] 但同样的错误 tar: "You must specify ..."
    【解决方案2】:

    除了@martriay 的回答,您还有一个错字——您写的是“20160822*.tar”,而您的文件格式是“20160822*.tar.gz”

    在应用shell=True 时,命令应该作为一个完整的字符串传递(参见documentation),如下所示:

    p=subprocess.Popen('tar -xzvf 20160822*.tar.gz', shell=True)
    

    如果你不需要p,你可以直接使用subprocess.call

    subprocess.call('tar -xzvf 20160822*.tar.gz', shell=True)
    

    但是我建议你使用更多的标准库,像这样:

    import glob
    import tarfile
    
    today = "20160822"  # compute your common prefix here
    target_dir = "/tmp"  # choose where ever you want to extract the content
    
    for targz_file in glob.glob('%s*.tar.gz' % today):
        with tarfile.open(targz_file, 'r:gz') as opened_targz_file:
            opened_targz_file.extractall(target_dir)
    

    【讨论】:

    • 是的,这是一个错字,我尝试解压缩然后解压缩,但同样的第一个问题。
    【解决方案3】:

    我找到了一种方法来做我需要的事情,而不是使用 os 命令,我使用了 python tar 命令并且它有效!

    import tarfile
    import glob
    
    os.chdir("/folder_to_scan/")
    for file in glob.glob("*.tar.gz"):
        print(file)
    
    tar = tarfile.open(file)
    tar.extractall()
    

    希望对您有所帮助。

    问候 马吉德

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-09-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-09
      • 2021-11-20
      • 1970-01-01
      • 2011-03-27
      • 1970-01-01
      相关资源
      最近更新 更多