Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
362 views
in Technique[技术] by (71.8m points)

fwrite - 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
" % (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

question from:https://stackoverflow.com/questions/65672064/put-the-float-number-in-f-write-in-python

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
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
" % (str(i + 1), char, char))
            else:
                msg.write("x%s %s %s
" % (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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...