在将数据追加到python中的.csv文件中时删除空行,每添加一次数据,行就会跳1空行

时间:2019-11-29 02:32:45

标签: python python-3.x

这是我的将数据附加到python中的csv的代码

public static int calculateMaxScore() {
    int rowscore = 0;
     for(int row=1; row<8; row++)
     {
        if (calculateRowScore(row) > rowscore) {
          rowscore = calculateRowScore(row);
        }
     }
     return rowscore; 
  }

如果我多次运行文件,csv就会像这样 the csv file

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()

我每次从python追加数据后如何删除空行

2 个答案:

答案 0 :(得分:0)

似乎airtemp以新行结尾。试试这个:

row = ['2014', '12', '31', '01', 'ADR', lat, lon, airtemp.strip()]

答案 1 :(得分:0)

最后我得到了答案hehehehehe。答案是在delimiter='\t',lineterminator='\n'上加上writer = csv.writer(csvFile).writerow(row),所以代码将像这样

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()

和此中的csv

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

会是这样

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