Jason Donnald Jason Donnald - 1 year ago 60
Python Question

issue in reading n number of values from a csv file header in python

I have a csv file (tab delimited) whose sample format is:

"col1 col2 col3 col4 col5"
"15 AMC 0.0 0.0 0.0"

Now I have a variable
which denotes the number of values that I want to read from the header of this csv file. So if
n = 3
so I want to read first 3 values in the header and form a list like
. I wrote this code to read tab delimited csv file but I am having some issue:

n = 3 # number of values to be extracted from header of csv.Will vary

file = open('file1.csv','rU')
read = csv.reader(file,delimiter='\t')

row_number = 0

for row in read:
if row_number == 0:
header = row

When I do
print header
I get
. How can I extract the
number of values from the header of the csv file?

Answer Source

I assume that the double quotes (") are in the file as you show them, so they will quote the whole line and delimiters are ignored within quoted strings. You would have to strip those quotes before handing the lines to the csv reader:

file = open('file1.csv','rU')

lines = [line.strip().strip('"') for line in file]  # strip white space, too, to be sure

read = csv.reader(lines, delimiter='\t')  
# any iterable producing strings will do in the reader constructor
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download