读取整个文件并加入第n行

时间:2014-03-18 15:19:51

标签: python file line-breaks

输入文件 -input.txt

entry1:name
entry1:description
entry1:reference_number
---
entry2:name
entry2:description
entry2:reference_number
---

输出文件 -output.txt

entry1:name entry1:description entry1:reference_number ---
entry2:name entry2:description entry2:reference_number ---

源代码

def line_break_join(infilepath, n):
    with open(infilepath) as infile:
    for i in range(1,4):
       print file.readline()

line_break_join("file1.txt", 4)

读完4行后我可以休息一下。此外,我想加入这4行并读取整个文件并加入4行,并相应地做。任何建议都将非常感激。谢谢。

3 个答案:

答案 0 :(得分:1)

一种可能的方式来看待这个:

def line_break_join(infilepath, n):
    with open(infilepath) as infile:
        #Read all the lines in the file, removing the line breaks
        lines = infile.read().splitlines() 

        #Grouping lines by pack of n
        pack = [lines[i:i+n] for i in range(0, len(lines), n)]

        #Joining each pack, putting a space between each string
        for subpack in pack:
            print " ".join(subpack)

答案 1 :(得分:0)

如果文件很大,一次读取所有行将无效。以下是一个可能的解决方案:

def read_write_batch(inpath, outpath, n):
    with open(inpath) as infile, open(outpath, 'w') as outfile:
        batch = []
        for line in infile:
            batch.append(line.strip())
            if len(batch) == n:
                outfile.write(':'.join(batch))
                outfile.write('\n')
                batch = []

if __name__ == '__main__':
    read_write_batch('/tmp/test.txt', '/tmp/out.txt', 4)

答案 2 :(得分:0)

这是一种方法:

def join(lines, n):
    it = iter(lines)
    while True:
        line = ' '.join(it.next().strip() for _ in range(n))
        if line:
            yield '%s\n' % line
        else:
            break  

with open(outfile, 'w') as out:
    out.writelines(join(open(infile), 4))