如何替换for循环中的行



我正在编辑的文件

45940736:1330:0.266667:1602990684:10023084.555000
48545806:16000000:0.000000:9999999999:0.000000
1191125008:1185:37.408333:1602991293:10282893.310000
116776982:1811:0.637500:1602990076:10022476.137000

我的代码

f = open("values", "r+")
lines = f.readlines()
for i in lines:
    if str(IDS) in i:
        spl = i.split(":")
        asset_id = spl[0]
        value = spl[1]
        volume = spl[2]
        updated = spl[3]
        item_age = spl[4]
        new_line = asset_id + ":" + "this is a test" + ":"+ volume + ":" + updated + ":" + item_age
        old_line = i
        print(new_line) 

在for循环中如何更换线路而不是进行

lines[0] = new_line
ff = open('values', 'w')
ff.writelines(lines)

我不能这么做,因为有些文件会有2k的值,我需要更改所有的值。

使用enumerate()以便在列表中获得索引,从而可以替换元素。

for index, i in enumerate(lines):
    if str(IDS) in i:
        spl = i.split(":")
        asset_id = spl[0]
        value = spl[1]
        volume = spl[2]
        updated = spl[3]
        item_age = spl[4]
        new_line = asset_id + ":" + "this is a test" + ":"+ volume + ":" + updated + ":" + item_age
        old_line = i
        lines[index] = new_line

最新更新