繁体   English   中英

如何从多个 zip 文件夹中的文本文件复制特定行?

[英]how to copy specific line from text files in multiple zip folders?

我正在尝试通过匹配部分字符串从 zip 文件夹中的文本文件复制行,zip 文件夹位于共享文件夹中,有没有办法从文本文件中复制字符串并将其发送到一个输出文本文件。 如何使用python做到这一点..是否可以使用zip_archive?

我尝试使用它,但没有运气。

zf = zipfile.ZipFile('C:/Users/Analytics Vidhya/Desktop/test.zip') 
# having First.csv zipped file.
df = pd.read_csv(zf.open('First.csv'))

@strava 的答案不同,您实际上不必提取... zipfile为您提供了用于操作文件的出色API 这是读取简单 zip 中每个文件的简单示例(我只压缩了一个.txt文件):

import zipfile
zip_path = r'C:\Users\avi_na\Desktop\a.zip'
niddle = '2'

zf = zipfile.ZipFile(zip_path) 
for file_name in zf.namelist():
    print(file_name, zf.read(file_name))
    if(niddle in str(zf.read(file_name))):
        print('found substring!!')

输出:

a.txt b'1\r\n2\r\n3\r\n'
found substring!!

使用此示例,您可以轻松地详细说明和读取每个文件,搜索文本中的字符串,并将其写入输出文件。

欲了解更多信息,检查printdir, read, write, open, close的成员zipfile.ZipFile

如果您只想提取然后使用pd.read_csv ,那也很好:

import zipfile
zip_path = r'...\a.zip'
unzip_dir = "unzip_dir"

zf = zipfile.ZipFile(zip_path) 
for file_name in zf.namelist():
    if '.csv' in file_name: # make sure file is .csv
        zf.extract(file_name, unzip_dir)
        df = pd.read_csv(open("{}/{}".format(unzip_dir,file_name)))

您可以尝试先提取它们,然后将它们视为普通的 csv 文件

zf = zipfile.ZipFile( path to zip )
zf.extract('first.csv', path to save directory )
file = open('path\first.csv')

这是一个执行我认为您需要的脚本 - 请注意,如果我们只想将字符串与行的内容进行匹配,我们不需要pandas ,如果您想在特定字段上进行匹配,则情况会有所不同,数值等——因此我没有使用pandas ......

$ cat zip.py
from sys import argv
from zipfile import ZipFile
'''
Usage python zip.py string ziparchive1 [ziparchive2 ...]
'''

def interesting(fn):
    # just an example
    return fn[-4:].lower() == '.csv'

script, text, zips = argv

if len(argv) == 3:
    # if 3 arguments, 'zips' is a string and iterating (below) on a
    # string gives us the individual characters in it, not exactly
    # what we want, hence we force it to be a list
    zips = [zips]

# iterate on archives' names    
for arch_name in zips:
    # instance a zipfile object
    archive = ZipFile(arch_name)
    # iterate on the names of contained files
    for file_name in archive.namelist():
        # skip directories
        if file_name[-1] == '/': continue
        if interesting(file_name):
            line_no = 0
            for line in archive.open(file_name):
                line_no += 1
                if text in line:
                    # here I just print the matching line, if you need
                    # something more complex you can use the
                    # 'arch_name', the 'file_name' and the 'line_no'
                    # to pinpoint the position of the matching line
                    print(line)
$ 

暂无
暂无

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

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