gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 02:00:06 25 4
gpt4 key购买 nike

我正在尝试从压缩文件复制所有 .txt 文件(该文件具有unknown_name_folders):.txt 文件位置 ---> my_path/?unknown_name_folder?/file.txt我想做 ---> my_path/file.txt

我执行了此代码,但出现此错误:EOFError:压缩文件在到达流结束标记之前结束。有什么想法吗?

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)

最佳答案

正如 Paulo 提到的,您第二次打开 tar 文件时错过了“gz”标志。另外,您复制文件的目标是原始 tarball - 我假设您希望将其放在单独的目录中(此处为“targdir”)

你只需要提取一次内容,所以代码变成:

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)

(编辑 - 您在“cp”命令中不需要“mypath” - 您已将 tarball 解压到当前目录中,因此“info.name!是文件的完整路径)

关于python - 将 .txt 文件从 .tar.gz 文件复制到其他目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49769562/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com