简体   繁体   中英

When i Write to csv file, the data gets written with commas separating each character in python

i am trying to read a csv file, then write the data to another one. when i do this, all the data that gets writtern is seperated by commas

here is my code:

with open(filenameInput, 'r') as csvfile:
dfi = pd.read_csv (filenameInput)
dfi - dfi.iloc[:-1]
print(dfi)


f = dfi['diagnosis(1=m, 0=b)'].gt(10)
f = str(f.bool)

t = dfi['diagnosis(1=m, 0=b)'].gt(-1)
t = str(t.bool)

morb = dfi['diagnosis(1=m, 0=b)'].gt(0)
morb = str(morb.bool)
print(morb)

if morb == f and chance > 35:

  with open(filename0, 'a+', newline='') as csvfile2:
    read = list(csv.reader(csvfile))
    print(read) 
    read = str(read)
    print("")
    print(read)
    read = read.replace("[['diagnosis(1=m, 0=b)', 'radius_mean', 'texture_mean', 'perimeter_mean', 'area_mean', 'smoothness_mean', 'compactness_mean', 'concavity_mean', 'concave points_mean', 'symmetry_mean', 'fractal_dimension_mean', 'radius_se', 'texture_se', 'perimeter_se', 'area_se', 'smoothness_se', 'compactness_se', 'concavity_se', 'concave points_se', 'symmetry_se', 'fractal_dimension_se', 'radius_worst', 'texture_worst', 'perimeter_worst', 'area_worst', 'smoothness_worst', 'compactness_worst', 'concavity_worst', 'concave points_worst', 'symmetry_worst', 'fractal_dimension_worst'], [", "")
    read = read.replace("]]", "")
    read = read.replace(" ", "")
    read = read.replace("'", [""])
    print(read)
    writer = csv.writer(csvfile2)
    writer.writerow(read)
    print("")
    print(list(read))

this is what gets written to the csv file:

0,",",9,.,5,0,4,",",1,2,.,4,4,",",6,0,.,3,4,",",2,7,3,.,9,",",0,.,1,0,2,4,",",0,.,0,6,4,9,2,",",0,.,0,2,9,5,6,",",0,.,0,2,0,7,6,",",0,.,1,8,1,5,",",0,.,0,6,9,0,5,",",0,.,2,7,7,3,",",0,.,9,7,6,8,",",1,.,9,0,9,",",1,5,.,7,",",0,.,0,0,9,6,0,6,",",0,.,0,1,4,3,2,",",0,.,0,1,9,8,5,",",0,.,0,1,4,2,1,",",0,.,0,2,0,2,7,",",0,.,0,0,2,9,6,8,",",1,0,.,2,3,",",1,5,.,6,6,",",6,5,.,1,3,",",3,1,4,.,9,",",0,.,1,3,2,4,",",0,.,1,1,4,8,",",0,.,0,8,8,6,7,",",0,.,0,6,2,2,7,",",0,.,2,4,5,",",0,.,0,7,7,7,3,],",",[,0,",",9,.,5,0,4,",",1,2,.,4,4,",",6,0,.,3,4,",",2,7,3,.,9,",",0,.,1,0,2,4,",",0,.,0,6,4,9,2,",",0,.,0,2,9,5,6,",",0,.,0,2,0,7,6,",",0,.,1,8,1,5,",",0,.,0,6,9,0,5,",",0,.,2,7,7,3,",",0,.,9,7,6,8,",",1,.,9,0,9,",",1,5,.,7,",",0,.,0,0,9,6,0,6,",",0,.,0,1,4,3,2,",",0,.,0,1,9,8,5,",",0,.,0,1,4,2,1,",",0,.,0,2,0,2,7,",",0,.,0,0,2,9,6,8,",",1,0,.,2,3,",",1,5,.,6,6,",",6,5,.,1,3,",",3,1,4,.,9,",",0,.,1,3,2,4,",",0,.,1,1,4,8,",",0,.,0,8,8,6,7,",",0,.,0,6,2,2,7,",",0,.,2,4,5,",",0,.,0,7,7,7,3

而不是writer.writerow(read) ,使用:

writer.writerow(read.split(','))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM