2

Suppose I have a txt file like below

3 113.12747240513697 -1.0352096627496632 14.963682795503324 
3 10.892386778099667 10.556798857881242 2.017821533523687 
2 15.532838824289408 11.761144702842378 -5.862336401808785 
2 10.892386778099667 10.556798857881242 2.017821533523687 
2 15.532838824289408 11.761144702842378 -5.862336401808785 
5 15.532838824289408 11.761144702842378 -5.862336401808785 
5 10.892386778099667 10.556798857881242 2.017821533523687 
5 15.532838824289408 11.761144702842378 -5.862336401808785

My goal is to change the first numbers.

  • 2 should be 0
  • 3 should be 1
  • 5 should be 2

Expected Output

1 113.12747240513697 -1.0352096627496632 14.963682795503324 
1 10.892386778099667 10.556798857881242 2.017821533523687 
0 15.532838824289408 11.761144702842378 -5.862336401808785 
0 10.892386778099667 10.556798857881242 2.017821533523687 
0 15.532838824289408 11.761144702842378 -5.862336401808785 
2 15.532838824289408 11.761144702842378 -5.862336401808785 
2 10.892386778099667 10.556798857881242 2.017821533523687 
2 15.532838824289408 11.761144702842378 -5.862336401808785 

My Solution

with open(traintypesdata) as f:
  for line in f:
    line[0] = line[0].replace('2','0')
    line[0] = line[0].replace('3','1')
    line[0] = line[0].replace('5','2')
    f.write(line[0])

I am getting:

TypeError: 'str' object does not support item assignment
Chris
  • 26,361
  • 5
  • 21
  • 42
drorhun
  • 500
  • 7
  • 22
  • 3
    ```line``` is a string. so ```line[0] = line[0].replace("2", "0")``` is equivalent to ```"2" = "2".replace("2", "0")```. – ewokx Oct 21 '22 at 06:03

1 Answers1

2

Strings in Python are immutable.

You can create a new modified line2 and then write it out.

with open(traintypesdata) as f:
  for line in f:
    first_char = '0' if line[0] == '2' else \
                 '1' if line[0] == '3' else \
                 '2' if line[0] == '5' else \
                 line[0]
    line2 = f"{first_char}{line[1:]}"
    f.write(line2)
Chris
  • 26,361
  • 5
  • 21
  • 42
  • Nice approach, code does not give any error, but there is no change in the txt file. – drorhun Oct 21 '22 at 06:31
  • 1
    Well, if `f` isn't opened for writing... You may want to create a list of lines and then write it out as a separate step, or write out to a different file. – Chris Oct 21 '22 at 06:33