插入文件的换行符第n行

时间:2014-02-07 21:52:42

标签: python file

我想给出一个文本文件的第n行。到目前为止,我想出了以下几点:

源代码

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)]

输入文件

50.000
0.6016
1.0000
100.00
0.7318
1.0000

输出文件

50.000
0.6016
1.0000

100.00
0.7318
1.0000

任何建议都会非常感激。谢谢。

3 个答案:

答案 0 :(得分:6)

你可以创建一个生成一个空字符串(或任何你想要的)每个n行的生成器:

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

list(breakn(lines, 3))

制作后,它确实取决于预期用途。要将其保存回文件:

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

答案 1 :(得分:0)

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()

答案 2 :(得分:0)

创建新文件:

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')

覆盖现有文件:

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')