Skip to content Skip to sidebar Skip to footer

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

Solution 1:

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.


Solution 2:

I would start by looking at the csv module.


Solution 3:

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.


Post a Comment for "Python To Insert Quotes To Column In CSV"