mihsathe
mihsathe

Reputation: 9154

Python loop doubt

I have a function called gett(int) that returns a series upon every call. It works fine when I write like this :

print gett(0)
print gett(1)

and so on..

but when I try to automate same in a for loop like this :

for a in range(28):
   print gett(a)

It works fine for only first value and I get following output:

[..series..]
[]
[]
[]
[]
..and all others empty

I am very very new to Python so this is might be very naive. Any help is highly appreciated. Thank you.

P.S. gett function :

trend = file("D:\\trend.csv", "r")

def gett(pos):
  t = []
  for x in trend:
      temp = x.split(',')
      temp = temp[4:]
      t.append(temp)

  t = t[25:]
  temp = []
  for a in t:
      if a[pos] != '':
          temp.append(a[pos])

  ############
  t = temp
  ############
  return t

Upvotes: 1

Views: 156

Answers (3)

Wooble
Wooble

Reputation: 90037

You're opening a file outside of the function definition, then trying to read from the global file object each time the function is run. After the first time running the function, the read pointer will be at the end of the file and you'll read nothing.

Either read the file each time through the function (seek to the start if you keep it global, or reopen it if you make it a local) or (almost certainly preferably, unless it's a huge file and memory is an issue) read the whole file into a list and operate on that list.

Upvotes: 3

Tim Pietzcker
Tim Pietzcker

Reputation: 336478

In the first iteration, you're reading the file completely.

In all subsequent iterations, the entire for x in trend: loop will therefore be skipped.

How about something like this:

import csv

def read_csv():
   with open("D:\\trend.csv", "rb") as f:
       trend = csv.reader(f, delimiter=",")
       temp = [row[4:] for row in trend]
       return temp[25:]

def gett(data, pos):
   return [a[pos] for a in data if a[pos] != ""]

Now you can do

>>> mydata = read_csv()
>>> gett(mydata, 0)
[1, 2, 3, 4]
>>> gett(mydata, 1)
[5, 6, 7, 8]

Upvotes: 4

Gautam
Gautam

Reputation: 7958

After the First Time you read the File The filePointer reaches the end of the File , So the next Time you try to read the file It just Skips it .

A better way of doing it would be

def gett(pos , filename):
  trend = file(filename, "r")
  t = []
  for x in trend:
      temp = x.split(',')
      temp = temp[4:]
      t.append(temp)

  t = t[25:]
  temp = []
  for a in t:
      if a[pos] != '':
          temp.append(a[pos])

  ############
  t = temp
  ############
  return t

You could Also try if size of file is small

arr = []
for x in file("path/to/file" ,"r")
     arr.append(x)

gett(pos , arr)

Upvotes: 0

Related Questions