سؤال

Input file-input.txt

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

Output file-output.txt

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

Source code

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)

I can give break after reading 4 lines. Furthermore I want to join those 4 lines and read thru entire file and join 4 lines each and do accordingly. Any suggestion will be greatly appreciate. Thanks.

هل كانت مفيدة؟

المحلول 2

Reading all the lines in one go will not be efficient if the file is large. Following is a possible solution:

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)

نصائح أخرى

One possible way to look at this:

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)

Here is a way to do it :

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))
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top