Swapping positions when reading a txt file

Viewed 52

I am reading a csv or txt file.

The csv or txt file has this format (can have several lines in the same format):

character , Int, character

And I want to change it to this format:

character , character , Int

and then save the new file as txt or csv.

I have this code to read a csv or txt file.

a_list=open(file)
for line in a_list:
  #line[1], line[2] = line[2], line[1] # Tried this line but didnt work
  print(line)

And I get this as result:

A,10,B
C,13,D

I want to change it to:

A,B,10
C,D,13

Whats the best way to do it?

SOLUTION

Using @DarrylG answer I changed the code to:

with open('edges.txt') as f:
    mylist = [line.rstrip('\n') for line in f]
    for line in mylist:
        line = line.split(',')              
        line[1], line[2] = line[2], line[1]  
        line = ','.join(line)               
        print(line) 
1 Answers

Strings are immutable. You need to split the line on comma to create a list whose elements can be changed.

Revised Code

with open('test.txt', 'r') as a_list:       # It's recommended to use a context manager 
                                            #  rather than naked open
    for line in a_list:
        line = line.rstrip().split(',')     # Remove trailing '/n' and split on ',' 
                                            # creating a list
        line[1], line[2] = line[2], line[1] # Interchange list elements based upon index
        line = ','.join(line)               # re-constructs the string
        print(line)                         # show result

Output

A,B,10
C,D,13
Related