Python growth note: Python3 uses the csv module csv.writer().writerow() to save the CSV file and generate a blank line solution

1. Problem background


During the test of the project, the data was saved to the csv file using the csv.writer().writerow() method. However, when checking the results, it was found that every time it was written, there would be an extra blank line. The problem is similar to the following:

Two, the source code before the problem


#!/usr/bin/python
#Author:千里之行
#Update:2020-09-04
#
#
#
#
import os
import sys
import csv
import time

def killProcessStressTest():
	with open('D:\\MemTest\\onemoreline.csv','w') as csvfile:
		writer = csv.writer(csvfile,dialect ='excel')
		writer.writerow(['time','MMSMem(KB)','MMSPid'])
		for i in range(loopNumber):
		    os.system(ipString)
		    time.sleep(3)
		    print(time.strftime("%Y-%m-%d %H:%M:%S",time.localtime())+">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>StressTest LoopNumber is:" + str(i))
		    mmsMemString = os.popen('adb shell "dumpsys meminfo |grep -e \'com.android.mms \' "')
		    mmsMemStringSplit = mmsMemString.read().strip().split(' ')
		    mmsMem = mmsMemStringSplit[0]
		    mmsPid = mmsMemStringSplit[4][:-3]
		    #print("mmsMem: "+mmsMem + " ;mmsPid: " +mmsPid)
		    time.sleep(2)

		    print(time.strftime("%Y-%m-%d %H:%M:%S",time.localtime())+ "MMSMem: "+mmsMem + " MMSPid: " + mmsPid )
		    #依次将关注进程的内存和Pid写入到csv文件中    
		    writer.writerow([time.strftime("%Y-%m-%d %H-%M-%S",time.localtime()),mmsMem,mmsPid])	    
		    time.sleep(5)
		csvfile.close()

if __name__ == "__main__":
    killProcessStressTest()

2. Solution


Later, by consulting the information, the problem was solved very well. Just add a newline=" parameter to the with statement. The code comparison before and after modification is as follows:

Guess you like

Origin blog.csdn.net/jinhoward/article/details/108445160