-4

Im sure this is a simple readlines solution. I have spent some time trying to solve it without success.

I have a block of text that reads:

"This is the text 1"
0.0 2.0 2.0 2.0    
0.0 0.0 4.0 0.0    
0.0 0.0 0.0 0.0    
0.0 0.0 0.0 0.0    
0.0 0.0 0.0 0.0    
0.0 0.0 0.0 0.0
"This is the text 2"
0.0 5.0 3.0 5.0    
0.0 0.0 6.0 0.0    
0.0 0.0 0.0 0.0    
0.0 0.0 0.0 0.0    
0.0 0.0 0.0 0.0    
0.0 0.0 0.0 0.0

and I am struggling to change it to:

"This is the text 1"
0.0 0.0 0.0 0.0    
0.0 0.0 0.0 0.0    
0.0 0.0 0.0 0.0    
0.0 0.0 0.0 0.0    
0.0 0.0 4.0 0.0    
0.0 2.0 2.0 2.0
"This is the text 2"
0.0 0.0 0.0 0.0    
0.0 0.0 0.0 0.0    
0.0 0.0 0.0 0.0    
0.0 0.0 0.0 0.0    
0.0 0.0 6.0 0.0    
0.0 5.0 3.0 5.0

Any help greatly appreciated. Thanks

Code:

f = open("file.txt", "rb")
    s = f.readlines()
    f.close()
    f = open("newtext.txt", "wb")
    f.writelines(s[::-1])
    f.close()

Returns the whole txt file inverted.

MB-F
  • 22,770
  • 4
  • 61
  • 116
ZachW
  • 48
  • 6
  • 3
    You're going to need to show us what type of code you have written so far, and where you are getting stuck. – Chris Aug 14 '17 at 14:17
  • Welcome to Stack Overflow, please take a time to go through [the welcome tour](https://stackoverflow.com/tour) to know your way around here (and also to earn your first badge), read how to [create a Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve) and also check [How to Ask Good Questions](https://stackoverflow.com/help/how-to-ask) so you increase your chances to get feedback and useful answers. – Josef Adamcik Aug 14 '17 at 14:24
  • @Chris apologies, my current method returns the whole file inverted, and i need to keep the headers "This is the text 1" in the same place – ZachW Aug 14 '17 at 14:31
  • @kazemakase sorry about the formatting, thanks – ZachW Aug 14 '17 at 14:49
  • @Qwerty no need to apologize. Just make sure I got it right ;) – MB-F Aug 14 '17 at 14:55

1 Answers1

0

This is working under the assumption that the number of rows between the text is always consistent.

# Open file, split on newlines into a list
with open('file.txt') as f:
    data = f.read().splitlines()
# Break list into multiple lists 7 items long
# this covers the text and the 6 sets of numbers that follow
newlist = [data[i:i + 7] for i in range(0, len(data), 7)]

output = []
# Append the text, then iterate backwards across each list, stopping short of the text
for item in newlist:
    output.append(item[0])
    for x in item[:0:-1]:
        output.append(x)
# output to text file, adding a newline character at the end of each row
with open('newtext.txt', 'w') as f:
    for item in output:
        f.write('{}\n'.format(item))
Chris
  • 15,819
  • 3
  • 24
  • 37