colin
colin

Reputation: 613

Re-ordering text file - Python

I must re-order an input file and then print the output to a new file.

This is the input file:

 The first line never changes.  
 The second line was a bit much longer.  
 The third line was short.  
 The fourth line was nearly the longer line.    
 The fifth was tiny.  
 The sixth line is just one line more.                  
 The seventh line was the last line of the original file. 

This is what the output file should look like:

 The first line never changes.                                            
 The seventh line was the last line of the original file.
 The second line was a bit much longer. 
 The sixth line is just one line more.
 The third line was short. 
 The fifth was tiny. 
 The fourth line was nearly the longer line.

I have code already that reverse the input file and prints it to the output file which looks like this

ifile_name = open(ifile_name, 'r')
lines = ifile_name.readlines()
ofile_name = open(ofile_name, "w")

lines[-1] = lines[-1].rstrip() + '\n'
for line in reversed(lines):
        ofile_name.write(line)
ifile_name.close()
ofile_name.close()

Is there anyway I can get the desired format in the text file while keeping my reverse code?

Such as print the first line of the input file, then reverse and print that line, the print the second line of the input file, then reverse and print that line etc.

Sorry if this may seem unclear I am very new to Python and stack overflow.

Thanks in advance.

Upvotes: 1

Views: 721

Answers (2)

Ahasanul Haque
Ahasanul Haque

Reputation: 11164

This is a much elegant solution I believe if you don't care about the list generated.

with open("ifile_name","r") as f:
    init_list=f.read().strip().splitlines()

with open("result.txt","a") as f1:
    while True:
        try:
            f1.write(init_list.pop(0)+"\n")
            f1.write(init_list.pop()+"\n")
        except IndexError:
            break

Upvotes: 1

Hooting
Hooting

Reputation: 1711

ifile_name = "hello/input.txt"
ofile_name = "hello/output.txt"
ifile_name = open(ifile_name, 'r')
lines = ifile_name.readlines()
ofile_name = open(ofile_name, "w")

lines[-1] = lines[-1].rstrip() + '\n'
start = 0
end = len(lines) - 1
while start < end:
    ofile_name.write(lines[start])
    ofile_name.write(lines[end])
    start += 1
    end -= 1
if start == end:
    ofile_name.write(lines[start])
ifile_name.close()
ofile_name.close()

use two pivots start and end to point which line to write to the file. once start == end, write the middle line to the file

Upvotes: 0

Related Questions