读一个文件直到空行,然后将读到的内容写入一个新的文本fi

2024-04-28 23:23:05 发布

您现在位置:Python中文网/ 问答频道 /正文

在abc.txt文档文件如下所示:

product/productId: B000179R3I
product/title: Amazon.com: Austin Reed Dartmouth Jacket In Basics, Misses: Clothing
product/price: unknown
review/userId: A3Q0VJTUO4EZ56

product/productId: B000GKXY34
product/title: Nun Chuck, Novelty Nun Toss Toy
product/price: 17.99
review/userId: ADX8VLDUOL7BG

product/productId: B000GKXY34
product/title: Nun Chuck, Novelty Nun Toss Toy
product/price: 17.99
review/userId: A3NM6P6BIWTIAE

我需要为上面的内容创建三个文本文件(注意:我这里有一个非常大的文件,例如我展示了三个)。在

^{pr2}$

Tags: txttitleproductpricereviewabcuseridtoy
2条回答

优化方式:

import os

def get_file(idx):
    ''' Opens file in write mode using `idx` arg as filename suffix.
        Returns the file object created
    '''
    fn = 'filename{}.txt'.format(idx)
    return open(fn, 'w')    

with open(os.path.normpath('C:\\Users\\abc.txt'), 'r') as f:
    idx = 1
    out_file = get_file(idx)
    for l in f:
        if not l.strip():
            out_file.close()
            idx += 1
            out_file = get_file(idx)
        else:
            out_file.write(l)

尝试将while(line!=""):替换为while(line!="\n"):

import os
filepath=os.path.normpath('C:\\Users\\abc.txt')
with open(filepath,'r') as rf:
    record = 1
    output = open('filename{}.txt'.format(record), 'w')
    for line in rf:
        if line == "\n":
            record += 1
            output.close()
            output = open('filename{}.txt'.format(record), 'w')
        else:
            output.write(line)

或者更简单:

^{pr2}$

相关问题 更多 >