this is my code for append data to csv in python
airtemp = rootgrp.variables['Tair_f_inst'][0][0][0]
lon = rootgrp.variables['lon'][0]
lat = rootgrp.variables['lat'][0]
row = ['2014', '12', '31', '01', 'ADR', lat, lon, airtemp]
with open('D:\Python\gg.csv', 'a') as csvFile:
writer = csv.writer(csvFile).writerow(row)
csvFile.close()
if i run the file many times the csv wiil be like this the csv file
Year,Month,Date,Time,plant,latitude,longitude,airtemp
2014,12,31,01,ADR,-2.375,115.375,297.5257
2014,12,31,01,ADR,-2.375,115.375,297.5257
2014,12,31,01,ADR,-2.375,115.375,297.5257
2014,12,31,01,ADR,-2.375,115.375,297.5257
2014,12,31,01,ADR,-2.375,115.375,297.5257
2014,12,31,01,ADR,-2.375,115.375,297.5257
2014,12,31,01,ADR,-2.375,115.375,297.5257
how can i remove that empty rows every i append the data from python
It seems that the airtemp
ends with a new line. Try this:
row = ['2014', '12', '31', '01', 'ADR', lat, lon, airtemp.strip()]
finally i got the answer hehehehehe. the answer is adding delimiter='\\t',lineterminator='\\n'
to writer = csv.writer(csvFile).writerow(row)
so the code will be like this
airtemp = rootgrp.variables['Tair_f_inst'][0][0][0]
lon = rootgrp.variables['lon'][0]
lat = rootgrp.variables['lat'][0]
row = ['2014', '12', '31', '01', 'ADR', lat, lon, airtemp]
with open('D:\Python\gg.csv', 'a') as csvFile:
writer = csv.writer(csvFile, delimiter='\t',lineterminator='\n',).writerow(row)
csvFile.close()
and the csv from this
Year,Month,Date,Time,plant,latitude,longitude,airtemp
2014,12,31,01,ADR,-2.375,115.375,297.5257
2014,12,31,01,ADR,-2.375,115.375,297.5257
2014,12,31,01,ADR,-2.375,115.375,297.5257
2014,12,31,01,ADR,-2.375,115.375,297.5257
2014,12,31,01,ADR,-2.375,115.375,297.5257
2014,12,31,01,ADR,-2.375,115.375,297.5257
2014,12,31,01,ADR,-2.375,115.375,297.5257
will be like this
Year,Month,Date,Time,plant,latitude,longitude,airtemp
2014,12,31,01,ADR,-2.375,115.375,297.5257
2014,12,31,01,ADR,-2.375,115.375,297.5257
2014,12,31,01,ADR,-2.375,115.375,297.5257
2014,12,31,01,ADR,-2.375,115.375,297.5257
2014,12,31,01,ADR,-2.375,115.375,297.5257
2014,12,31,01,ADR,-2.375,115.375,297.5257
2014,12,31,01,ADR,-2.375,115.375,297.5257
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.