Reputation: 313
So this is my code:
import csv
particle_counter = file('C:/Users/Desktop/Level 2 files/HiSAM1_data_160206_134230.csv','rU')
gas_csv = file('C:/Users/Desktop/Level 2 files/gas_0.csv','rU')
gps_csv = file('C:/Users/Desktop/Level 2 files/gps_0.csv','rU')
pm2_5_csv = file('C:/Users/Desktop/Level 2 files/pm25_0.csv','rU')
reader1 = csv.reader(particle_counter)
reader2 = csv.reader(gas_csv)
reader3 = csv.reader(gps_csv)
reader4 = csv.reader(pm2_5_csv)
def skipline(n,filename):
x =0
while x < n in filename:
reader = csv.reader(filename)
result = next(reader)
return result
print(skipline(0,particle_counter) )
I've been trying to know how do you skip headers to files that have different number of headers in one single function. However, I think i got what i need in order to do that but when i run the program i get:
In[21]: %run "C:/Users/Desktop/Level 2 files/skiplinefunction.py"
None
What i expected to happen was that the function would take each file and skip the number of header lines that each individual file has until it reaches values. I tried printing one file to see if it skiped the lines on that file but i got the None. What does that mean? is there anything wrong in my program that I can't seem to see? How can i fix this?
Upvotes: 0
Views: 45
Reputation: 1123560
skipline()
returned it, and you printed it. And skipline()
returned it because your while
test can never be True
:
while x < n in filename:
The expression x < n in filename
is a chained comparison, and is executed as x < n and n in filename
. x < n
is already false since both x
and n
are both 0
, but the test n in filename
is also false because 0
is never going to be an element in a string sequence.
The function then just ends without an explicit return
, so the default return None
is executed instead, and you print that result.
If you wanted to skip a certain number of rows in your CSV file, do so directly on either the open file object (to skip lines that the CSV reader should not parse) or on the reader objects. You don't need to pass in a filename for that. Use the consume
recipe from the itertools recipes section; for your case that comes down to using next(islice(iterator, n, n), None)
, see Python CSV reader to skip 9 headers.
Applied to your function that'd be:
from itertools import islice
def skiplines(reader, n):
next(islice(reader, n, n), None)
and use this directly on the reader objects:
skiplines(particle_counter, 1)
The function does not return anything.
Upvotes: 2
Reputation: 1934
In the skipline()
function:
def skipline(n,filename):
x =0
while x < n in filename:
reader = csv.reader(filename)
result = next(reader)
return result
x = 0
and n = 0
. So nothing is being parsed as x < n
evaluates to False
. The function thus returns the default value of None
.
Upvotes: 0