简体   繁体   中英

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

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]

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()

Try this:

import csv

with open('TAB.csv', 'rb') as f, open('out.txt', 'wb') as g:
    reader = csv.reader(f)
    next(reader)            # skip header
    g.writelines(row[3] + '\n' for row in reader)

enumerate is a nice function that returns a tuple. It enables to to view the index while running over an iterator.

import csv
with open('NEW.txt','wb') as outfile:
    with open('TAB.csv','rb') as f:
        reader = csv.reader(f)
        for index, row in enumerate(reader):
           if index > 0:
               outfile.write(row[3])
               outfile.write("\n")

Another solution would be to read one line from the file (in order to skip the header).

It's an old question but I would like to add my answer about Pandas library, I would like to say. It's better to use Pandas library for such tasks instead of writing your own code. And the simple code with Pandas will be like :

import pandas as pd
reader = pd.read_csv('TAB.csv', header = None)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM