3

I've got a text file that is structured like so

1\t 13249\n
2\t 3249\n
3\t 43254\n
etc...

It's a very simple list. I've got the file opened and I can read the lines. I have the following code:

count = 0
for x in open(filename):
 count += 1
return count

What I want to do is to assign the first number of each line to a variable (say xi) and to assign the second number of each line to another variable (yi). The goal is to be able to run some statistics on these numbers.

Many thanks in advance.

asked Aug 31, 2011 at 5:19
1
  • 2
    Check out the numpy package first. Commented Aug 31, 2011 at 5:40

4 Answers 4

4

No need to reinvent the wheel..

import numpy as np
for xi, yi in np.loadtxt('blah.txt'):
 print(xi)
 print(yi)
answered Aug 31, 2011 at 5:31
Sign up to request clarification or add additional context in comments.

3 Comments

this depends on numpy, which is not builtin
i do use statistics for stuffs beyond mickey mouse, but still never felt the need for numpy... (partly because they were so long to support python 3). and note that there is no need to get aggressive when i just point out to the OP that your solution depends on an external package which have to be manually downloaded and installed, stuff which do not blow in front of your eyes when you are not used to python.
ok but in the case of this question, are you advocating not using a library which makes the job easier, when the same thing can be done in a roundabout way with builtins? i would say one of the best things about python is the existence and ease of use of many mature and powerful libraries such as numpy.
2
count = 0
for x in open(filename):
 # strip removes all whitespace on the right (so the newline in this case)
 # split will break a string in two based on the passed parameter
 xi, yi = x.rstrip().split("\t") # multiple values can be assigned at once
 count += 1
return count
answered Aug 31, 2011 at 5:21

1 Comment

this will give xi, yi as strings when the OP has said they want to run some statistics on numbers. i think it's overcomplicating things.
2
>>> with open('blah.txt') as f:
... for i,xi,yi in ([i]+map(int,p.split()) for i,p in enumerate(f)):
... print i,xi,yi
... 
0 1 13249
1 2 3249
2 3 43254

note that int(' 23\n') = 23

this is clearer: Note that enumerate provides a generator which includes a counter for you.

>>> with open('blah.txt') as f:
... for count,p in enumerate(f):
... xi,yi=map(int,p.split()) #you could prefer (int(i) for i in p.split())
... print count,xi,yi
... 
0 1 13249
1 2 3249
2 3 43254
answered Aug 31, 2011 at 7:01

Comments

-1

with regular expression:

import re
def FUNC(path):
xi=[]
yi=[]
f=open(path).read().split("\n") # spliting file's content into a list
patt=re.compile("^\s*(\d)\t\s(\d).*") # first some whitespaces then first number
#then a tab or space second number and other characters 
for iter in f:
 try:
 t=patt.findall(iter)[0]
 xi.append(t[0])
 yi.append(t[1])
 except:
 pass
print xi,yi
#-----------------------------
if __name__=="__main__":
FUNC("C:\\data.txt")

a simpler code:

def FUNC(path):
x=[]
y=[]
f=open(path).read().split("\n")
for i in f:
 i=i.split(" ")
 try:
 x.append(i[0][0])
 y.append(i[1][0])
 except:pass
print x,y

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.