Python Forum
flipping the for loop in file - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: flipping the for loop in file (/thread-13565.html)



flipping the for loop in file - juniorcoder - Oct-21-2018

Hello friends ,
I save the output of my python code in a txt. file . In this file I have many variables , like x[t][m]...y[t][m]...I[t][m].
For another code ,
1)I need to read just x and y variables in my solution file.
2)I have to flip the for loop while reading .
Let me give you an example:
In solution file it is like this:
x[1][1]=3
x[1][2]=5
x[1][3]=9
x[2][1]=3
x[2][2]=5
x[2][3]=9
What I need:

x[1][1]=3
x[2][1]=5
x[3][1]=9
x[1][2]=3
x[2][2]=5
x[3][2]=9

I never done this type of reading file with this manner . Can you give some ideas or example ? Thank you so much


RE: flipping the for loop in file - ichabod801 - Oct-21-2018

You can find the lines you need to change with line.startswith('x'). You could then find the locations of the brackets with line.index, using the start parameter. Or you could make a regex that finds a number in brackets, and use regex.findall(line) to get the brackets, and reverse them. The regex is probably easier.


RE: flipping the for loop in file - wavic - Oct-21-2018

>>> left, right = 'x[1][2]=5'.split('][')
>>> left, right = left[:-1] + right[0], left[-1] + right[1:]
>>> new_line = ']['.join((left, right))
>>> new_line
'x[2][1]=5'
>>>