Question

I have a file with data, i.e.

2 3 5 6

I want to calculate (2+3)/5 and extend the resulting value after 6 with \'t'. i.e

2 3 5 6 1

How to do this? I wrote a code, but it only appends the value at the end of list I get smth like this

2 3 5 6
 1

f=open('file', 'r')
lines=f.readlines()
import re 
for line in lines:
    new_list=re.split(r'\t+',line)
    a=new_list[0]
    b=new_list[1]
    c=new_list[2]
    d=new_list[3]
    y=((float(a)+float(b))/float(c))*100
    y=round(xy,1)
    y=str(y) 
    new_list.append(y)
    r=open('result', 'a')
    x='\t'.join(new_list)
    x=x+'\n'
    r.writelines(x)
f.close()
r.close()
Was it helpful?

Solution

This is somewhat unrelated to your attempted solution, but it's how I'd approach the problem. I really try to avoid regex when possible, and it's definitely possible to do so in your case.

The first line takes your file and names it f (and automatically closes the file when we're done with it). Then I split your data and put it into a list, splitting each time there's a space. Initially, the output is strings, so I make those into floats. Then I do the weird calculation you want based on the numbers in my list, and print the output.

with open('nums.txt','r') as f:
    line = f.readline()
    list_of_nums = line.split(" ")
    myNums = [float(num) for num in list_of_nums]
    weird_calculation = (myNums[0] + myNums[1]) / myNums[2]
    print(str(weird_calculation) + "\t" + str(myNums[3]))

Output:

1.0     6.0

If you want only some of these numbers to be treated as floats and others as ints, you'll have to explicitly change that.

OTHER TIPS

Just added a line.strip, sometimes this tiny things make it all work

f=open('file', 'r')
lines=f.readlines()
import re 
for line in lines:
    new_list=re.split(r'\t+',line.strip())
    a=new_list[0]
    b=new_list[1]
    c=new_list[2]
    d=new_list[3]
    y=((float(a)+float(b))/float(c))*100
    y=round(xy,1)
    y=str(y) 
    new_list.append(y)
    r=open('result', 'a')
    x='\t'.join(new_list)
    x=x+'\n'
    r.writelines(x)
f.close()
r.close() 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top