Python 3.x 用python 3替换文本文件中所有行的第一个字符

Python 3.x 用python 3替换文本文件中所有行的第一个字符,python-3.x,Python 3.x,我有这样一个txt文件: 2 0.306250 0.376667 0.085000 0.120000 3 0.416250 0.385833 0.090000 0.118333 4 0.354375 0.509167 0.091250 0.121667 2 0.198125 0.206667 0.091250 0.123333 我想用0、1、2、0分别替换第一批租船人,即每条航线的2、3、4、2。为此,我编写了一个python脚本: with open('WIN_20210421_15_46_

我有这样一个txt文件:

2 0.306250 0.376667 0.085000 0.120000
3 0.416250 0.385833 0.090000 0.118333
4 0.354375 0.509167 0.091250 0.121667
2 0.198125 0.206667 0.091250 0.123333
我想用0、1、2、0分别替换第一批租船人,即每条航线的2、3、4、2。为此,我编写了一个python脚本:

with open('WIN_20210421_15_46_55_Pro.txt') as file:
    lines = file.readlines()
for item in lines:
    strs = item.strip('\n')
    if strs[0] == 2:
        strs[0].replace(str(2), str(0))
    elif strs[0] == 3:
        strs[0].replace(str(3), str(1))
    else:
        strs[0].replace(str(4), str(1))
脚本没有给我与out相同的输入文件。如何使用相同的文件名获得所需的输出?比如:

0 0.306250 0.376667 0.085000 0.120000
1 0.416250 0.385833 0.090000 0.118333
2 0.354375 0.509167 0.091250 0.121667
0 0.198125 0.206667 0.091250 0.123333
replace()。它返回一个新字符串,因此您必须将其分配回我的示例(
line
)中的
item


非常感谢,这很有帮助
lines_in = [
    "2 0.306250 0.376667 0.085000 0.120000\n",
    "3 0.416250 0.385833 0.090000 0.118333\n",
    "4 0.354375 0.509167 0.091250 0.121667\n",
    "2 0.198125 0.206667 0.091250 0.123333\n"
]

for line in lines_in:
    first_char = line[0]
    if first_char == "2":
        line = line.replace("2", "0", 1)
    elif first_char == "3":
        line = line.replace("3", "1", 1)
    elif first_char == "4":
        line = line.replace("4", "2", 1)

    print(line)