簡體   English   中英

如何在 Python 中讀取壓縮文件夾中的文本文件

[英]How to read text files in a zipped folder in Python

我有一個壓縮的數據文件(都在一個文件夾中,然后壓縮)。 我想在不解壓縮的情況下閱讀每個文件。 我嘗試了幾種方法,但沒有任何方法可以在 zip 文件中輸入文件夾。 我應該如何做到這一點?

zip 文件中沒有文件夾:

with zipfile.ZipFile('data.zip') as z:
  for filename in z.namelist():
     data = filename.readlines()

用一個文件夾:

with zipfile.ZipFile('data.zip') as z:
      for filename in z.namelist():
         if filename.endswith('/'):
             # Here is what I was stucked

namelist()以遞歸方式返回存檔中所有項目的列表。

您可以通過調用os.path.isdir()來檢查項目是否為目錄:

import os
import zipfile

with zipfile.ZipFile('archive.zip') as z:
    for filename in z.namelist():
        if not os.path.isdir(filename):
            # read the file
            with z.open(filename) as f:
                for line in f:
                    print line

希望有幫助。

我讓亞歷克的代碼工作。 我做了一些小的編輯:(注意,這不適用於受密碼保護的 zipfile)

import os
import sys
import zipfile

z = zipfile.ZipFile(sys.argv[1])  # Flexibility with regard to zipfile

for filename in z.namelist():
    if not os.path.isdir(filename):
        # read the file
        for line in z.open(filename):
            print line
        z.close()                # Close the file after opening it
del z                            # Cleanup (in case there's further work after this)

我讓 RichS 的代碼起作用了。 我做了一些小的編輯:

import os
import sys
import zipfile

archive = sys.argv[1] # assuming launched with `python my_script.py archive.zip`

with zipfile.ZipFile(archive) as z:    
    for filename in z.namelist():
        if not os.path.isdir(filename):
            # read the file
            for line in z.open(filename):
                print(line.decode('utf-8'))

如您所見,編輯很小。 我已經切換到 Python 3,ZipFile 類有一個大寫的 F,並且輸出從 b 字符串轉換為 unicode 字符串。 僅當您嘗試解壓縮文本文件時才進行解碼。

PS 我一點也不反對 RichS。 我只是覺得這會很有趣。 既實用又溫和。 PPS 您可以使用密碼從存檔中獲取文件: ZipFile.open(name, mode='r', pwd=None, *, force_zip64=False)ZipFile.read(name, pwd=None) 如果您使用.read則沒有上下文管理器,因此您只需執行

            # read the file
            print(z.read(filename).decode('utf-8'))

暫無
暫無

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

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