如何在for循环中替换行

时间:2020-10-27 00:17:46

标签: python python-3.x file

我正在编辑的文件

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的值,我需要更改所有值。

1 个答案:

答案 0 :(得分:1)

使用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