mujahir
mujahir

Reputation: 187

Read a file till empty line and write what was read to a new text file

the abc.txt file looks like this:

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

I need to create three text file for the above(Note: I have got a very large here for example I have shown for three) .

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)

Upvotes: 1

Views: 9119

Answers (2)

duyue
duyue

Reputation: 778

Try replacing while(line!=""): with 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)

Or simpler:

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

Upvotes: 0

RomanPerekhrest
RomanPerekhrest

Reputation: 92894

Optimized way:

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)

Upvotes: 2

Related Questions