Extracting information from files

I have a file, the content is in the format of

41545
0
0
1
2
3
3
3
...


Following is the code

X=[]
Y=[]
total=0
count=0
for line in open(file,'r'):
count+=1
line=line.strip()
if(line.strip()):
if(count==1):
total=int(line)
else:
X.append(count-1)
Y.append(int(line))


the output for the above code is

total=41545 #first line
X=[1,2,3,4,5,6,7] #count of second line onwards
Y=[0,0,1,2,3,3,3] #second line onwards information


Is there a shorter and hopefully more efficient code that can achieve the same purpose?

migrated from stackoverflow.comOct 13 '14 at 12:42

This question came from our site for professional and enthusiast programmers.

Build a generator over the file to return just ints, then transpose the enumeration to get your X and Y, eg:

with open('testing.txt') as fin:
lines = (int(line) for line in fin)
total = next(lines)
X, Y = zip(*enumerate(lines, 1))


Note X and Y will be tuples instead of lists, but you can convert them after if you wish.

• clean and efficient – Anzel Oct 9 '14 at 16:31

There certainly is!

Try this:

Y=[]

with open(file, 'r') as fd:

for line in fd:
line=line.strip()
if(line):
Y.append(int(line))


X is superfluous because it my be calculated by

pos = 4 #Index of an element in Y
y_value = Y[pos]
x_value = pos + 1 #X value of that element


Where pos is the index of an element of Y that you would like the X value for

This should do the trick. Read the first line by itself and convert to int. Then read the remaining lines via list comprehension. Then you can just generate the line numbers based on the number of values read in.

with open(file, 'r') as f: