读取文件直到空行并将读取的内容写入新的文本文件

时间:2017-10-23 08:32:57

标签: 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

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

import os
filepath=os.path.normpath('C:\\Users\\abc.txt')
with open(filepath,'r') as rf:
    for index,line in enumerate(rf):
        with open ('filename{}.txt'.format(index),'w') as output:
            while(line!=""):
                output.write(line)

2 个答案:

答案 0 :(得分:1)

优化方式:

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)

答案 1 :(得分:0)

尝试将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)

或更简单:

awk -v RS= '{print > ("filename" NR ".txt")}' abc.txt