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:

  1. 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.
  2. 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.


Need Your Help

How to animate the camera in three.js to look at an object?

rotation three.js quaternions

In Three.js, I would like to have the camera looking at an object in the scene, and when I click on another object, to have the camera rotate smoothly to look at the new object. (i.e animate the ro...

LazyReference with double-checked locking and null handling

java null volatile lazy-initialization double-checked-locking

I've been using LazyReference class for a few years (not on a regular basis of course, but sometimes it is very useful). The class can be seen here. Credits go to Robbie Vanbrabant (class author) and

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.