0

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

  • 1
    Does this answer your question? [Safely evaluate simple string equation](https://stackoverflow.com/questions/43836866/safely-evaluate-simple-string-equation) – Random Davis Jan 11 '21 at 17:53

1 Answers1

0
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.

Synthase
  • 5,849
  • 2
  • 12
  • 34
  • Thanks:). I've accepted your previous response, but it was closed. I don't know why. Thanks again. –  Jan 11 '21 at 17:57
  • No problem. You can accept this one tho! (I think you did upvote it, which is cool, but you can click on the gray tick below the up/down stuff to accept :) ) – Synthase Jan 11 '21 at 17:59