python line written with comma comprising writerow, automatically add extra double quotes

When the operation of the CSV file, writes a line of text with WriteRow, if the line of text (character string) contains a comma, and then automatically beginning of the line end of the line (character string two) double quotes. Recommended for write write.

temp.csv file line 2 contains a comma :

TimeStamp=2019-02-13
1232a,abc
rmUID1
2234
22345

code:

# -*- coding: utf-8 -*-
import csv
from itertools import islice
oldf = open('temp.csv','r',newline='')
newf = open('temp2.csv','w',newline='')
nf = csv.writer(newf,lineterminator='\n')
for line in islice(oldf,0,5):
    listn = []
    line = line.strip('\n')
    listn.append(line)
    print(listn)
    nf.writerow(listn)
oldf.close()
newf.close()

display:

['TimeStamp=2019-02-13\r']
['1232a,abc\r']
['rmUID1\r']
['2234\r']
['22345']
 

The actual file in temp2.csv second line automatically add double quotation marks :

TimeStamp=2019-02-13
"1232a,abc "
rmUID1
2234
22345
 

After modifying the code:

import csv
from itertools import islice
oldf = open('temp.csv','r',newline='')
newf = open('temp2.csv','w',newline='')
for line in islice(oldf,0,5):
    line = line.strip('\n')
    newf.write(line)
oldf.close()
newf.close()

The outcome document:

TimeStamp=2019-02-13
1232a,abc
rmUID1
2234
22345

The problem is resolved.

Guess you like

Origin blog.csdn.net/lekmoon/article/details/87776892