Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read a column without header from csv and save the output in a txt file using Python?

Tags:

python

csv

I have a file "TAB.csv" with many columns. I would like to choose one column without header (index of that column is 3) from CSV file. Then create a new text file "NEW.txt" and write there that column (without header).

Below code reads that column but with the header. How to omit the header and save that column in a new text file?

import csv
with open('TAB.csv','rb') as f:
    reader = csv.reader(f)
    for row in reader:
        print row[3]
like image 353
zone1 Avatar asked Jan 03 '15 01:01

zone1


People also ask

How do I read a CSV file without column heading in Python?

To read CSV file without header, use the header parameter and set it to “None” in the read_csv() method.

How do I save a CSV file without the header?

To write DataFrame to CSV without column header (remove column names) use header=False param on to_csv() method.


1 Answers

This is the solution @tmrlvi was talking: it skips the first row (header) via next function:

import csv

with open('TAB.csv','rb') as input_file:
    reader = csv.reader(input_file)
    output_file = open('output.csv','w')
    next(reader, None)

    for row in reader:
        row_str = row[3]
        output_file.write(row_str + '\n')

    output_file.close()
like image 183
avenet Avatar answered Oct 06 '22 00:10

avenet