Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
372 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 Reply

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...