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?
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With