gpt4 book ai didi

python - 如何在 python 中使用 linux 命令遍历 .tar.gz 文件列表

转载 作者:太空宇宙 更新时间:2023-11-04 10:47:25 25 4
gpt4 key购买 nike

使用 python 2.7

我在 linux 机器上有一个 *.tat.gz 文件列表。使用 python,我想遍历文件并将这些文件提取到不同位置,在它们各自的文件夹下。

For example: if my file name is ~/TargetData/zip/1440198002317590001.tar.gz
then I want to untar and ungzip this file in a different location under its respective folder name i.e. ~/TargetData/unzip/1440198002317590001.

我已经编写了一些代码,但我无法遍历这些文件。在命令行中,我可以使用 $ tar -czf 1440198002317590001.tar.gz 1440198002317590001 命令解压缩。但我希望能够遍历 .tar.gz 文件。代码在下面提到。在这里,我不能只循环文件或只打印文件。你能帮忙吗?

    import os
inF = []
inF = str(os.system('ls ~/TargetData/zip/*.tar.gz'))
#print(inF)
if inF is not None:
for files in inF[:-1]:
print files
"""
os.system('tar -czf files /unzip/files[:-7]')
# This is what i am expecting here files = "1440198002317590001.tar.gz" and files[:-7]= "1440198002317590001"
"""

您曾经处理过此类用例吗?非常感谢您的帮助!!谢谢!

最佳答案

我认为你误解了os.system()的意思,它会完成工作,但它的返回值不是你所期望的,成功完成返回0,你不能直接将其输出分配给一个变量。您可以考虑模块 [subprocess],请参阅文档 here .但是,我不推荐这种方式来列出文件(实际上,它返回字符串而不是列表,请参阅文档自行查找详细信息)。

我认为最好的方法是 glob 模块,参见文档 here .使用glob.glob(pattern),您可以将所有匹配该模式的文件放在一个列表中,然后您可以轻松地循环它。

当然,如果你熟悉os模块,你也可以使用os.listdir(), os.path.join(),甚至 os.paht.expanduser() 来执行此操作。 (与glob不同,它只是将没有完整路径的文件名放入列表中,您需要重建文件路径)。

顺便说一下,为了您的目的,不需要先声明一个空列表(即 inF = [])

对于解压文件部分,你可以通过os.system来完成,但我也建议使用subprocess模块而不是os.system >,你会在subprocess的文档中找到原因。


不要看下面的代码,只有当你实在无法自己解决这个问题时才看。

import os
import glob

inF = glob.glob('~/TargetData/zip/*.tar.gz')
if inF:
for files in inF:
# consider subprocess.call() instead of os.system
unzip_name = files.replace('zip', 'unzip')[:-7]
# get directory name and make sure it exists, otherwise create it
unzip_dir = os.path.dirname(unzip_name)
if not os.path.exists(unzip_dir):
os.mkdir(unzip_dir)
subprocess.call(['tar -xzf', files, '-C', unzip_name])
# os.system('tar -czf files /unzip/files[:-7]')

关于python - 如何在 python 中使用 linux 命令遍历 .tar.gz 文件列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32493455/

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