ryszard eggink
ryszard eggink

Reputation: 335

Leaving just the first column in the csv file using python

I am trying to leave just the first column of a csv file. But it seems not to be working for me and can not find the working solution.

def leavethefirstcolumn(filename):
    with open(filename) as f, open('out.csv', "w") as out:
        reader = csv.reader(f)
        for row in reader:
            out.write(row[0])

Upvotes: 0

Views: 202

Answers (1)

Jean-Louis Mbaka
Jean-Louis Mbaka

Reputation: 1612

import csv

def leavethefirstcolumn(filename):
  with open(filename) as file, open('out.csv', "w") as out:
    reader = csv.reader(file)
    for row in reader:
      out.write(row[0] + "\n")

# example of using the function
leavethefirstcolumn("in.csv")
  1. You are calling csv.reader(file) while on the previous line, you wrote with open(filename) as f instead of with open(filename) as file.
  2. Also when you are writing to out, you should add a new line character '\n'

Upvotes: 3

Related Questions