简体   繁体   English

Python Zip文件读取

[英]Python Zip Files Read

I am new to python, I have a .zip file which has multiple sub-folders and each sub-folders has multiple .txt files. 我是python的新手,我有一个.zip文件,其中包含多个子文件夹,每个子文件夹都有多个.txt文件。 I am trying to read all .txt files But I want to store files folder specific into a variable But I am not able to do so. 我正在尝试读取所有.txt文件,但我想将特定于文件夹的文件文件夹存储到变量中,但是我无法这样做。

For eg: "test.zip" which has three folders "a","b","c", each has multiple(>10,000) .txt files I want to read all files inside folder "a" and store it into a variable a_file and same with folder "b" and "c" I tried the following code: 例如:“ test.zip”具有三个文件夹“ a”,“ b”,“ c”,每个都有多个(> 10,000).txt文件,我想读取文件夹“ a”内的所有文件并将其存储到变量a_file,与文件夹“ b”和“ c”相同,我尝试了以下代码:

for file in os.listdir():
if file.endswith('test.zip'):
    zfile=zipfile.ZipFile(file)
    fnames= [f.filename for f in zfile.infolist()]
    for subfile in fnames:
        if fnames == "a" . #name of a folder 
          if subfile.endswith('.txt'):
              lines=zfile.open(subfile).read()
              print(lines)

But the code is extracting all files from multiple folders and not displaying any output maybe because of if condition it. 但是代码从多个文件夹中提取了所有文件,并且可能由于if条件而未显示任何输出。 Instead of a reading folder specific and storing it Thank You in Advance for helping 而不是特定的阅读文件夹并存储它,先谢谢您的帮助

That happened because zip file lists the files as follows: 发生这种情况是因为zip文件将文件列出如下:
a/a1.txt a/a2.txt b/b1.txt b/b2.txt a / a1.txt a / a2.txt b / b1.txt b / b2.txt
So you need to separate files from directory using split('/') 因此,您需要使用split('/')将文件与目录分开
You could try this: 您可以尝试以下方法:

import os
from zipfile import ZipFile
for file in os.listdir():
    if file.endswith('test.zip'):
        zfile = ZipFile(file);
        fnames = [f.filename for f in zfile.filelist];
        for subfile in fnames:
            dir_name = subfile.split('/')[0];
            if(dir_name == 'a'):
                if(subfile.endswith('.txt')):
                    lines = zfile.open(subfile).read();
                    print(lines);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM