Home > Mobile >  swapping position of two specific numbers in a text file python?
swapping position of two specific numbers in a text file python?

Time:10-29

I want to swap two numbers position on each line of the text file after i replace equal symbol with this '|' and save it, but I'm having trouble to do that! For instance

123456789=123456789

i wanted it to look like this:

123453489=126756789

As you can see, I swapped 34 with 67!

This is my code:

with open('track.txt', 'r') as z:
 data = z.read()
 
data = data.replace('=', '|')
  
with open('track2.txt', 'w') as z:
  z.write(data)

Thank you very much! Sorry for my English.

CodePudding user response:

Use a regular expression with capture groups, so you can copy to the replacement in a different order.

import re

with open('track.txt', 'r') as z:
    data = z.read()
 
data = re.sub(r'^(.{5})(.{2})(.*)=(.{2})(.{2})(.*)$', r'\1\5\3|\4\2\6', data, flags=re.MULTILINE)

with open('track2.txt', 'w') as z:
    z.write(data)

The re.MULTILINE flag makes ^ and $ match the beginning and end of each line.

If you don't like regular expressions, you can do it with slicing and concatenation in a loop.

new_data = ''

for line in data.splitlines():
    fields = line[:5], line[5:7], line[7:10], line[11:13], line[13:15], line[15:]
    new_data  = fields[0]   fields[4]   fields[2]   '|'   fields[3]   fields[1]   fields[5]
  • Related