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 rowsto variable newrow
forrowin csvReader:
newrow.append(row)
# Add quotes around the third list item
forrowin newrow:
row[2] = "'"+str(row[2])+"'"
csvFileRead.close()
# Create a new CSV file
csvWriter = csv.writer(csvFileNew, delimiter =',')
# Append the csv withrowsfrom newrow variable
forrowin 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'withopen(filename, 'wb') as f:
reader = csv.reader(f)
forrowin 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"