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.
-
2Check out the numpy package first.Keith– Keith2011年08月31日 05:40:20 +00:00Commented Aug 31, 2011 at 5:40
4 Answers 4
No need to reinvent the wheel..
import numpy as np
for xi, yi in np.loadtxt('blah.txt'):
print(xi)
print(yi)
3 Comments
numpy.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
1 Comment
xi, yi as strings when the OP has said they want to run some statistics on numbers. i think it's overcomplicating things.>>> 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
Comments
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