Search code examples
pythonfwritetxt

Put the float number in f.write in python


I have a text file with (100 rows and 2 columns) like:

1 2
2 3 

I want to change each row to a text file as follow:

x1 1 1*2
x2 2  4

x1 2 4
x2 3 6

I have used this code for doing that:

with open("data.txt", "r") as msg:
    data = msg.readlines()

output = 0
for line in data:
    with open(str(output)+"_parameter.txt", "w") as msg:
        for i, char in enumerate(line.strip().split()):
            msg.write("x%s %s %s*2\n" % (str(i + 1), char, char))
output += 1

Its works well. But the problem is that, in the txt file which created, the number saved as

x1 1 1*2 
x2 2 2*2 

x1 2 2*2 
x2 3 3*2 

But I want to save the float number for example instead of (2*2), I want the (4) in the text file. Not the string. Could you help me to solve this? thank you


Solution

  • with open("data.txt", "r") as msg:
        data = msg.readlines()
    
    output = 0
    for line in data:
        with open(str(output)+"_parameter.txt", "w") as msg:
            for i, char in enumerate(line.strip().split()):
                if i == 0:
                    msg.write("x%s %s %s*2\n" % (str(i + 1), char, char))
                else:
                    msg.write("x%s %s %s\n" % (str(i + 1), char, str(int(char)*2)))
    output += 1
    

    Hi back :). Here you make the computation for each third col x*y excepted if first line.