How can I add quotes and a tab to every element in a csv file using python?
For example, I want to make this csv sample:
TitleA,TitleB,TitleC,TitleD,TitleE,....
Data1,Data2,,Data4,,....
DataX,,,DataY,,....
Look like this:
"TitleA" "TitleB" "TitleC" "TitleD" "TitleE" ....
"Data1" "Data2" "" "Data4" "" ....
"DataX" "" "" "DataY" "" ....
I am essentially converting a csv file into a tab separated file where all the elements are enclosed in single quotes...
Is there a quick method to do this?
Any help is appreciated!
解决方案
What you're doing is converting from one CSV dialect to another, right?
So, you do that by defining two CSV dialects, and creating a reader for one and a writer for the other.
And fortunately, these dialects are both simple enough (the input is even the default) that you don't need to do anything fancy:
with open('in.csv', 'r') as infile, open('out.csv', 'w') as outfile:
reader = csv.reader(infile)
writer = csv.writer(outfile, delimiter='\t', quoting=csv.QUOTE_ALL)
writer.writerows(reader)
In very old versions of Python, you may have to replace that last line with two:
for line in reader:
writer.writerow(line)