Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read a CSV file and put double quote on each item in python

Tags:

python

csv

I'm really new to python and I have a simple question. I have a .csv file with the following content:

123,456,789

I want to read it and store it into a variable called "number" with the following format

"123","456","789"

So that when I do

print number

It will give the following output

"123","456","789"

Can anybody help?

Thanks!

Update: The following is my code:

input = csv.reader(open('inputfile.csv', 'r'))
for item in input:
    item = ['"' + item + '"' for item in item]
print item

It gave the following output:

['"123"', '"456"', '"789"']
like image 556
user1546610 Avatar asked Sep 11 '25 04:09

user1546610


1 Answers

Here's how to do it:

import csv
from io import StringIO

quotedData = StringIO()

with open('file.csv') as f:
    reader = csv.reader(f)
    writer = csv.writer(quotedData, quoting=csv.QUOTE_ALL)
    for row in reader:
       writer.writerow(row)

with reader=csv.reader(StringIO('1,2,3')) the output is:

print quotedData.getvalue()
"1","2","3"
like image 93
tzelleke Avatar answered Sep 13 '25 17:09

tzelleke