将结果写入excel电子表格中的新列

大家好,
我想出了一个如何读取.csv文件、对其中一列中的值执行简单命令,然后将结果打印到命令提示符屏幕上的解决方案
但是,如果我希望将结果写入写出(目标)文件中的新列,该怎么办?我相信这不是一个用EXCEL方言读/写.csv文件的罕见功能吗?
以下是我的代码:

选择 | 换行 | 行号
  1. import csv 
  2. sourcefile = open('H:/LoadData.csv', 'rb')
  3. outfile = open('H:/LoadData_out.csv', 'wb')
  4. source = csv.reader(sourcefile, dialect='excel') #tells the program what format sourcefile is in
  5. dest = csv.writer(outfile, dialect='excel') #tells the program what format the destination file is in
  6.  
  7. for lst in source:  #define csv file as a matrix, Python starts at zero.  Columns are skipped, hence, LOAD is column 5, not column 3
  8.     print lst[0], lst[1], lst[2], lst[3]  # TIME, DIR, LOCATION, LOAD
  9.     x = float(lst[3])     #define LOAD as an integer
  10.     try:
  11.         if x >= 20:
  12.             print 'load greater than 20'
  13.             dest.writerow(lst)
  14.         else:
  15.             print 'load less than 20'
  16.  
  17.     except ValueError:   #error handling...if value is null or not in the correct format
  18.         print 'value null', repr(lst)    #returns list as a parseable object
  19.  

它打印出的内容(部分):
下午3:45:00出境商业广告和迈尔斯22.80
负荷大于20
下午3:45:00出境商业和农村22.90
负荷大于20
下午3:45:00出境商业和Vista 19.50
负载小于20
下午3:45:00出境商业广告和马德罗纳18.80
负载小于20
下午3:45:00出境商业广告和布朗宁18:00
负载小于20
下午3:45:00出境商业及迎新20:00
负荷大于20
下午3:45:00出境商业和希尔菲克19.00
负载小于20
下午3:45:00出境商业和KEGLERS 17.80
负载小于20
我希望它将这些结果导出到LoadData_out.csv文件中,并在一个新列中使用'Load is instant/less 20'语句.
提前谢谢!

标签: python

添加新评论