python - Reading entire file and join nth line -
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): open(infilepath) infile: in range(1,4): print file.readline() line_break_join("file1.txt", 4) i can give break after reading 4 lines. furthermore want join 4 lines , read thru entire file , join 4 lines each , accordingly. suggestion appreciate. thanks.
reading lines in 1 go not efficient if file large. following possible solution:
def read_write_batch(inpath, outpath, n): open(inpath) infile, open(outpath, 'w') outfile: batch = [] 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)
Comments
Post a Comment