简体   繁体   English

将.txt文件从.tar.gz文件复制到其他目录

[英]Copy .txt files from a .tar.gz file to other directory

I am trying to copy all the .txt files from a compressed file (this file has unknown_name_folders): .txt files location ---> my_path/?unknown_name_folder?/file.txt I want to do ---> my_path/file.txt 我正在尝试从压缩文件中复制所有.txt文件(此文件具有unknown_name_folders):.txt文件位置---> my_path /?unknown_name_folder?/file.txt我想做---> my_path / file。文本

I did this code, but I have this error: EOFError: Compressed file ended before the end-of-stream marker was reached. 我做了这段代码,但是出现了这个错误:EOFError:压缩文件在到达流结束标记之前结束。 Any idea? 任何想法?

file=my_path+"/"+fil
if file.endswith('.tar.gz'):

    tarf = tarfile.open(file, "r:gz")
    for info in tarf:

        if info.name.endswith('.txt'):
            print(info.name)

            tar = tarfile.open(file) #extracting
            tar.extractall()
            tar.close()    
            code=os.system('cp ' + my_path+'/'+info.name +' '+ file)

As Paulo mentioned, you missed off the "gz" flag the second time you opened the tar file. 如Paulo所述,您在第二次打开tar文件时错过了“ gz”标志。 Also, your target for copying the file was the original tarball - I assume you wanted it in a separate directory ("targdir" here) 另外,您复制文件的目标是原始的tarball-我假设您希望将其放在单独的目录中(此处为“ targdir”)

You only need to extract the contents once, so the code becomes: 您只需要提取一次内容,代码就会变成:

file=my_path+"/"+fil
targdir='dest'
if file.endswith('.tar.gz'):

    tarf = tarfile.open(file, "r:gz")
    tarf.extractall()
    for info in tarf:

        if info.name.endswith('.txt'):
            print(info.name)
            code=os.system('cp ' + info.name +' '+ targdir)

(edit - you don't need 'mypath' in the "cp" command - you have extracted the tarball into the current directory, so "info.name! is the full path to the file) (编辑-您不需要在“ cp”命令中使用“ mypath”-您已将压缩包解压缩到当前目录中,因此“ info.name!”是文件的完整路径)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM