'Appending a random number at the end of every row in a file using Python [duplicate]

I have a file say, file.txt, which looks like:

1,2,3,4
5,6,7,8
1,4,3,6

Now I want to add an extra column with every row of that file which will be any random number between 0.51 to 0.99

I am trying the below code:

import random
with open('file.txt', 'r') as input:
    with open('outfile.txt', 'w') as output:
        for line in input:
            line = line.rstrip('\n') + ',' + random.uniform(0.51, 0.99)
            print(line, file=output)

But here I am getting an error saying :

TypeError: can only concatenate str (not "float") to str



Solution 1:[1]

The error message is telling you that you cannot add a string and a float - you need to convert the float to a string first, like this:

line = line.rstrip('\n') + ',' + str(random.uniform(0.51, 0.99))

or if you want to use an f-string to format it you can do it a couple ways

line = line.rstrip('\n') + ',' + f"{random.uniform(0.51, 0.99):.2f}"
line = f"{line.rstrip('\n')},{random.uniform(0.51, 0.99):.2f}"

Solution 2:[2]

change line = line.rstrip('\n') + ',' + random.uniform(0.51, 0.99) to line = line.rstrip('\n') + ',' + str(random.uniform(0.51, 0.99))

Solution 3:[3]

Use a format string or wrap the random number in a str object

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Whereismywall
Solution 3 Metareven