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 :
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 you can do it a couple ways
line = line.rstrip('\n') + ',' + f"{random.uniform(0.51, 0.99)}"
line = f"{line.rstrip('\n')},{random.uniform(0.51, 0.99)}"