Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Data Science by (18.4k points)
recategorized by

This is the File I am editing:

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

This is my Code

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) 

How would I replace my line in the for loop instead of doing

lines[0] = new_line

ff = open('values', 'w')

ff.writelines(lines)

I can't do that because some files will have the 2k values and I need to change all of them.

1 Answer

0 votes
by (36.8k points)
edited by

Use the enumerate() so you get a index in the list, so you can replace a element.

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

Do check out the Data Science which will help you understand Data Science from scratch.

Browse Categories

...