簡體   English   中英

我有一個包含許多.tar.gz文件的文件夾。 在python中,我想進入每個文件解壓縮或壓縮,並找到具有要提取的字符串的文本文件?

[英]I have a folder with many .tar.gz files. In python I want to go into each file unzip or compress and find text file that has string I want to extract?

我的主文件夾包含許多gz.tar壓縮文件。 因此,我需要解壓縮兩次以獲取帶有文本的數據文件,然后在文本中提取特定的字符串。 我無法解壓縮以獲取包含文本的文件,然后移至下一個文件並執行相同操作。 將結果保存在數據框中。

import os
import tarfile
for i in os.listdir(r'\user\project gz'):
 tar = (i, "r:gz")
 for m in tar.getmembers():
  f= tar.extractfile(member):
  if f is not None:
   content = f.read()
   text = re.findall(r"\name\s", content)
   df = pd.Dataframe(text)
   print(df)

我猜您想在\\user\\project gz\\*.tar.gz找出包含字符串\\name\\s文件嗎?

一個解決方案是

import os
import re
import tarfile

import pandas as pd

row = []
value = []


for filename in os.listdir(r'\\user\\project gz'):
    if filename.endswith('.tar.gz'):
        tar = tarfile.open(r'\\user\\project gz' + filename)
        for text_file in tar.getmembers():
            f = tar.extractfile(text_file)
            if f is not None:
                content = f.read().decode()
                if re.findall(r"\\name\\s", content):
                    row.append(text_file.name)
                    value.append(content)
        tar.close()


df = pd.DataFrame(value, columns=['nametag'], index=row)
print(df)

暫無
暫無

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

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