# How to extract data in *.txt file and use it in Python?

I have a Python code that converts (u,v)to (s,d):

def d2r(d): r = d * math.pi / 180.0 return (r) def r2d(r): d = r * 180.0 / math.pi return (d) def sd2uv(s,d): r = d2r(d) u = s * math.sin(r) v = s * math.cos(r) return (u,v) def uv2sd(u,v): s = math.sqrt((u*u)+(v*v)) r = math.atan2(u,v) d = r2d(r) if d < 0: d = 360 + d return (s,d)

The u data are stored in u.txt, each line has one number; the v data are stored in v.txt and each line has one number too. My question is how to extract data from these two files and then use them in the Python code to print (s,d)? Thanks!

## Answers

I think this should do it:

with open('u.txt') as uf, open('v.txt') as vf: for u,v in zip(uf,vf): print uv2sd(float(u),float(v))

from itertools import izip, imap with open('u.txt') as u_data, open('v.txt') as v_data: for u,v in imap(float, izip(u_data, v_data)): print uv2sd(u, v)

I can imagine two ways of doing this:

- Read all of the data from each file into two separate lists. Iterate through both lists and compute each value until you reach the end of one of the lists.
- Read one line from each file at a time. Compute the value you are looking for. Repeat until you have exhausted both files.

The first point has the advantage of saving the data for subsequent use (if needed) without having to open & read the files again. This may not work well at all if you have a very large data set in the file.

The second point has the advantage of saving some memory if you only need to use the data once in the program. This could be slower if you need to use the data over-and-over again.

The first way may look like this:

with open('u.txt') as u_file, open('v.txt') as v_file: u_values = u_file.readlines() v_values = v_file.readlines() for u, v in zip(u_values, v_values): print uv2sd(float(u), float(v)) # We can use u_values and v_values again if we need to now

The second way is what Akavall and gnibbler came up with.