Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSV writer prints extra quotes

Tags:

python

I am learning Python script. I want to read a TSV file and print the result in a particular format like below,

Input file [tab separated]:

1   john   henry   1.234 

Output:

1,
"john",
"henry",
1.234

I wrote the below code.

tsvfile = csv.reader(open('input.tsv' , 'r'), delimiter='\t')
outfile = csv.writer(open('output.txt' , 'w+'), escapechar='\"', quoting=csv.QUOTE_NONE)

row_number = 1
for row in tsvfile:
  outfile.writerow([row[0]+","])    
  outfile.writerow(['"'+row[1]+'"'+","])
  outfile.writerow(['"'+row[2]+'"'+","])
  outfile.writerow([row[3]])
  row_number = row_number + 1

It generates the output as

1,
""john""",
""henry""",
1.234

The script prints ", instead of , and "" instead of ". I am trying to understand this behavior.

Can anyone help me why my scripts prints extra " everywhere? How should I generate the expected output?

like image 955
Anit Avatar asked Oct 23 '25 07:10

Anit


1 Answers

Maybe do this, i just read the CSV file and then got trough each line and then split it and then join it with ',\n' (and don't forget to use repr):

with open('filname.csv','r') as f, open('outfilename.txt','w') as f2:
   l=[',\n'.join(repr(x) for x in i.split()) for i in f]
   f2.write('\n'.join(l))

If no need cotes, do:

with open('filname.csv','r') as f, open('outfilename.txt','w') as f2:
   l=[',\n'.join(i.split()) for i in f]
   f2.write('\n'.join(l))
like image 169
U12-Forward Avatar answered Oct 25 '25 21:10

U12-Forward



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!