Python Forum

Full Version: flipping the for loop in file
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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
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.
>>> 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'
>>>