RydallCooper
RydallCooper

Reputation: 21164

Python Enclosing Words With Quotes In A String

For Python I'm opening a csv file that appears like:

    jamie,london,uk,600087
    matt,paris,fr,80092
    john,newyork,ny,80071

How do I enclose the words with quotes in the csv file so it appears like:

    "jamie","london","uk","600087"
    etc...

What I have right now is just the basic stuff:

    filemame = "data.csv"
    file = open(filename, "r")

Not sure what I would do next.

Upvotes: 0

Views: 245

Answers (1)

Burhan Khalid
Burhan Khalid

Reputation: 174624

If you are just trying to convert the file, use the QUOTE_ALL constant from the csv module, like this:

import csv

with open('data.csv') as input, open('out.csv','w') as output:
    reader = csv.reader(input)
    writer = csv.writer(output, delimiter=',', quoting=csv.QUOTE_ALL)
    for line in reader:
        writer.writerow(line)

Upvotes: 1

Related Questions