AzaRoth91
AzaRoth91

Reputation: 283

Python to insert quotes to column in CSV

I have no knowledge of python. What i want to be able to do is create a script that will edit a CSV file so that it will wrap every field in column 3 around quotes. I haven't been able to find much help, is this quick and easy to do? Thanks.

column1,column2,column3
1111111,2222222,333333

Upvotes: 0

Views: 3343

Answers (3)

Antoine Pietri
Antoine Pietri

Reputation: 813

import csv
filename = 'file.csv'
with open(filename, 'wb') as f:
    reader = csv.reader(f)
    for row in reader:
        row[2] = "'%s'" % row[2]

And then write it back in the csv file.

Upvotes: 0

Flint
Flint

Reputation: 44

This is a fairly crude solution, very specific to your request (assuming your source file is called "csvfile.csv" and is in C:\Temp).

import csv

newrow = []
csvFileRead = open('c:/temp/csvfile.csv', 'rb')
csvFileNew = open('c:/temp/csvfilenew.csv', 'wb')

# Open the CSV
csvReader = csv.reader(csvFileRead, delimiter = ',')

# Append the rows to variable newrow
for row in csvReader:
    newrow.append(row)

# Add quotes around the third list item
for row in newrow:
    row[2] = "'"+str(row[2])+"'"

csvFileRead.close()

# Create a new CSV file
csvWriter = csv.writer(csvFileNew, delimiter = ',')

# Append the csv with rows from newrow variable
for row in newrow:
    csvWriter.writerow(row)

csvFileNew.close()

There are MUCH more elegant ways of doing what you want, but I've tried to break it down into basic chunks to show how each bit works.

Upvotes: 2

NPE
NPE

Reputation: 500893

I would start by looking at the csv module.

Upvotes: 0

Related Questions