我有下面的代码片段,我想将date:07/12/13
分开并将其写入csv文件。但是,我无法从列表中分离元素。我已经在.py脚本上测试了列表组件,它工作正常,但是当我运行脚本时它会出错。
def main():
pass
if __name__ == '__main__':
main()
count=0
f=open("test.csv","w+");
result = csv.writer(f,delimiter=',', dialect='excel-tab')
result_statememt=("date","time","Zenith","Azimuth","Elevation","conv_elevation");
result.writerow(result_statememt)
f.close()
while(count<5):
#time.sleep(60)
ser=serial.Serial()
ser.port=2
ser.baudrate=9600
ser.open()
str=ser.read(109)
print str
val=str.split(":")
print val
print "\n"
lines=str.split("\r\n")
print lines
wst=[]
print line
wst=[]
for line in lines[:]:
line=lines.split(":")
print line
f=open("test.csv","a+")
result=csv.writer(f,delimiter=',')
count=count+1
#lines=str.split("\r\n")
#print count
#f=open("test.txt","a+")
#result=csv.writer(f,delimiter=',')
#result.writerow()
f.close()
f.close()
ser.close()
程序的输出窗口:
Serial.port received data:
date is:7/12/16
time is:24-0-0
Zenith:104.85
Azimuth:110.40
Elevation:-14.85
Converted Elevation:15.79
val out put :
['date is', '7/12/16\r\ntime is', '24-0-0\r\nZenith', '104.85\r\nAzimuth', '110.40\r\nElevation', '-14.85\r\nConverted Elevation', '15.79\r\n']
lines output:
['date is:7/12/16', 'time is:24-0-0', 'Zenith:104.85', 'Azimuth:110.40', 'Elevation:-14.85', 'Converted Elevation:15.79', '']
答案 0 :(得分:0)
相关缺失的代码是:
import csv
with open('some.csv', 'wb') as f:
writer = csv.writer(f)
writer.writerows(someiterable)
你是不用iteratable写作所以失败了。此外,您只应打开一次文件并将其关闭 一次 。
答案 1 :(得分:0)
以下是我对您的问题的理解:
让我们开始尝试处理一组数据(6行),然后才能处理更多数据。据我所知,一组数据可能如下:
date is:7/12/16
time is:24-0-0
Zenith:104.85
Azimuth:110.40
Elevation:-14.85
Converted Elevation:15.79
这些行是\r\n
,但这并不重要。假装我们通过以下方式获取数据:
>>> data = 'date is:7/12/16\r\ntime is:24-0-0\r\nZenith:104.85\r\nAzimuth:110.40\r\nElevation:-14.85\r\nConverted Elevation:15.79'
如果我们按行拆分数据:
>>> data.splitlines()
['date is:7/12/16', 'time is:24-0-0', 'Zenith:104.85', 'Azimuth:110.40', 'Elevation:-14.85', 'Converted Elevation:15.79']
现在,我们可以在冒号处分割每一行:
>>> [line.split(':')[1] for line in data.splitlines()]
['7/12/16', '24-0-0', '104.85', '110.40', '-14.85', '15.79']
上面说过,*对于我们数据中的每一行,我们在冒号处分割线并取第二部分(第一部分在索引0处,第二部分在索引1处)。这是我们要写入输出文件的行。
现在我们知道如何处理这条线,我们可以把它放在一个循环中(在你的情况下是5次)。此外,我通过将串行端口启动代码放在开头来清理代码。这样,我们只初始化一次并关闭一次。这是代码:
import csv
if __name__ == '__main__':
# Init serial line
ser = serial.Serial()
ser.port = 2
ser.baudrate = 9600
ser.open()
with open('test.csv', 'w+') as f:
result = csv.writer(f, delimiter=',', dialect='excel')
result.writerow(['date','time','Zenith','Azimuth','Elevation','conv_elevation']);
for count in range(5):
data = ser.read(109)
row = [line.split(':')[1] for line in data.splitlines()]
result.writerow(row)
ser.close()