Replace same string with random numbers on the same file

Question:

I want to be able to replace the same set of string to random new unique numbers.

From:

color = { 0 0 0 }

To:

color = { 2 5 10 }

color = { 1 59 102 }

color = { 9 72 200 }

On each line of the text file.

Here’s my python code.

import random

for i in range(0, 10):
    x = str(random.randrange(0, 256))
    y = str(random.randrange(0, 256))
    z = str(random.randrange(0, 256))

    with open("9.txt", "r") as file:
        file_data = file.read()

    file_data = file_data.replace("color = { 0 0 0 }", "color = { " + x + " " + y + " " + z + " }")

    with open("colored.txt", "w") as file:
        file.write(file_data)

This code changes all correctly but to the same values and I want it to be unique numbers.

Asked By: Fĭř ÛŠ

||

Answers:

You need to process the file line by line, not all at once, and generate new random numbers for each line.

with open("9.txt", "r") as infile, open("colored.txt", "w") as outfile:
    for line in infile:
        x = str(random.randrange(0, 256))
        y = str(random.randrange(0, 256))
        z = str(random.randrange(0, 256))
        line = line.replace("color = { 0 0 0 }", f'color = {{ {x} {y} {z} }}')
        outfile.write(line)
Answered By: Barmar
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.