簡體   English   中英

如何遍歷目錄並解壓縮tar.gz文件?

[英]How to loop through directories and unzip tar.gz files?

我有一些包含...tar.gz文件的子目錄。 我正在嘗試使用os.walk()瀏覽各個文件,並使用tarfile模塊將其解壓縮。

import os
import tarfile

current_wkd = os.getcwd()

output_dir = '.../Tar_unzip/output'

for dirpath, dir, files in os.walk(top=current_wkd):
    #print(files) produces
    #alpha.tar.gz
    #beta.tar.gz
    #...etc
    for file in files:
        tar = tarfile.open(file)   #this line produces an error:'file cannot be opened' 
        tar.extractall(path=output)
        tar.close() 

我試圖遍歷不同的目錄並提取..tar.gz文件。 我也嘗試使用:

...
for file in files:
if file.endswith('.gz'):  #find files that end with .gz 
    #some folders contain other files
    #that may result in an error? 
    tar = tarfile.open(file)
    tar.extractall(path=output_dir)

我真的對python是否可用於在目錄中移動(迭代)並執行某些功能(例如解壓縮文件等)感興趣。

任何幫助深表感謝。 我是Python的新手。 謝謝。

os.walk文檔中所述:

請注意,列表中的名稱不包含路徑成分。 要獲取dirpath中文件或目錄的完整路徑(從頂部開始),請執行os.path.join(dirpath, name)

當然,您可以自己看到打印出alpha.tar.gz等的確切信息,這些顯然不是當前工作目錄中的絕對路徑名或相對路徑名,也不是您可以訪問的其他任何東西,僅僅是空文件名。

還要注意,文檔中給出的每個示例都完全符合建議。 例如:

import os
for root, dirs, files in os.walk(top, topdown=False):
    for name in files:
        os.remove(os.path.join(root, name))
    for name in dirs:
        os.rmdir(os.path.join(root, name))

因此,在您的情況下:

for dirpath, dir, files in os.walk(top=current_wkd):
    for file in files:
        tar = tarfile.open(os.path.join(dirpath, file))
        tar.extractall(path=output)
        tar.close()

還有一件事:

output_dir = '.../Tar_unzip/output'

這幾乎肯定會導致錯誤。 一方面, outputoutput_dir是不同的名稱。 另一方面, ...並不意味着什么。 您可能想要..

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM