insert a line break nth line of a file

I want to give a break nth line of a text file. So far I come up with followings:

Source Code

def line_break_file(foo):
        with open(foo) as f:
            lines = f.readlines()
            [' '.join(lines[3 * i: 3 * i + 3]) for i in range(0, len(3) / 3)]

Input File

50.000
0.6016
1.0000
100.00
0.7318
1.0000

Output File

50.000
0.6016
1.0000

100.00
0.7318
1.0000

Any suggestion will be greatly appreciate. Thanks.

Answers


You could make a generator that yields an empty string (or whatever you want) every n lines:

def breakn(lines, n, sep=''):
    for line in lines:
        if not line % n:
            yield sep
        yield line

list(breakn(lines, 3))

It really depends on the intended use after making it. To save it back to a file:

with open('newfile.txt', 'w') as newfile:
    for line in breakn(lines, 3, '\n'):
        newfile.write(line)

def line_break_file(foo):
    f = open(foo)
    lines = f.read().split()
    for i in range(len(lines)):
       if not i % n:
           print
       print lines[i]
    f.close()

To create a new file:

def lineBreak(infilepath, outfilepath, n):
    with open(infilepath) as infile, open(outfilepath, 'w') as oufile:
        for i,line in enumerate(infile):
            outfile.write(line)
            if not i%n:
                outfile.write('\n')

To overwrite an existing file:

def lineBreak(infilepath, n):
    with open(infilepath) as infile:
        lines = infile.readlines()
    with open(infilepath, 'w') as outfile:
        for i,line in enumerate(lines):
            outfile.write(line)
            if not i%n:
                outfile.write('\n')

Need Your Help

How do you change the folder and menu font-size in Sublime Text 3?

ide sublimetext sublimetext3

I'm not talking about the font-size of the editor window, simply the font-size of the text in the main menu bar and the folder/file navigation side panel.

Sync between two tables

ios objective-c sqlite sqlite3

I am working with sqlite DB in iOS. I have two tables named LEVEL and SUBJECT.