Reputation: 159
I have a file with this format:
611 2856 618 2582 94075 94107 94065 94068
101071 94104
598 2856 618 611 93995 94107 93992 93991
94075 94065
612 2834 2821 2812 94087 101577 94085 94081
101558 101557
I need to read the lines and to rewrite them so:
611 2856 618 2582 94075 94107 94065 94068 101071 94104
598 2856 618 611 93995 94107 93992 93991 94075 94065
612 2834 2821 2812 94087 101577 94085 94081 101558 101557
I have tried something like this:
f2 = open('new_file.txt', 'w')
f1 = open('old_file.txt')
lines = f1.readlines()
for i, line in enumerate(lines):
print(repr(line))
f2.write(line)
i = i+1
f1.close()
f2.close()
But it is not working as it writes again every line. I need to read two lines and write them in one. Any suggesitons?
Upvotes: 2
Views: 878
Reputation: 55499
You don't need to read the lines into a list, or mess about with line numbers, you can just iterate directly over the file lines:
with open('oldfile.txt') as fin, open('newfile.txt', 'w') as fout:
for line in fin:
fout.write(line[:-1] + ' ' + next(fin))
contents of newfile.txt
611 2856 618 2582 94075 94107 94065 94068 101071 94104
598 2856 618 611 93995 94107 93992 93991 94075 94065
612 2834 2821 2812 94087 101577 94085 94081 101558 101557
line[:-1] + ' '
removes the newline char at the end of the long lines, and replaces it with a single space; I'm pretty sure that this is faster than doing line.replace('\n', ' ')
, but I haven't timed it.
As with Graipher's solution, if the file doesn't have an even number of lines, then the last line will not be copied, but I assume that's not an issue for your data.
Upvotes: 4
Reputation: 73498
The lines returned by readlines
still contain the newline '\n'
at the end. You must strip
them:
with open('new_file.txt', 'w') as f2:
with open('old_file.txt') as f1:
lines = f1.readlines()
# lines = f1.read().splitlines() will even save you the stripping
for i, line in enumerate(lines): # line: 'foo bar \n'
f2.write(line.strip())
if i % 2: # linebreak only every other line
f2.write('\n')
Upvotes: 1
Reputation: 7206
You can use a buffer variable to store every second line like so:
with open('new_file.txt', 'w') as fout:
with open('old_file.txt') as fin:
buffer = ""
for i, line in enumerate(fin):
if i % 2 == 0:
buffer = line.replace('\n', '')
else:
fout.write(sep.join((buffer, line)))
buffer = ""
With sep = " "
or whatever else you use for separation.
This assumes you have an even number of lines, otherwise the last line will not be written.
Upvotes: 1