2014-06-16 69 views
0

我从一个csv获取数据并获取2个不同的变量,这些变量是不同格式的位置,一个用于单层,另一个用于多个楼层。我的代码拉数据工作正常,我有麻烦写在第二个CSV正确的行,数据正在写,但它是这样做的字母。从一个csv获取输入并写入第二个csv

import csv 
infile = open('vlan_dev.csv', 'rU') 
reader = csv.reader(infile) 
outfile = open('testout.csv', 'w') 
writer = csv.writer(outfile) 
used_header = False 
for row in reader: 
    # skip over the CSV header 
    if not used_header: 
     used_header = True 
     continue 

    #defining variables 
    building = row[3] 
    startfloor = row[4] 
    endfloor = row[5] 
    subnet = row[6] 
    mask = row[10] 
    location1 = building.replace(' ', '')+startfloor 
    location2 = building.replace(' ', '')+startfloor+'-'+endfloor 
    iprange = subnet+'/'+mask 
    if (building != 'NETWORK CORE' and subnet.startswith('10.96.')): 
     if startfloor == endfloor: 
      print location1 
      writer.writerow(location1) 
     elif startfloor != endfloor: 
      print location2 
      writer.writerow(location2) 
     location = location1 + location2 
     print location 

我已经尝试了第二部分的几个选项,并有麻烦写入正确。上面提到了正确的输出,但是每个单元格写入一个字母。我尝试了其他的选择,但是很茫然。

回答

2

writerow需要一个可迭代的,并且字符串是逐个字符迭代的。试试:

writer.writerow([location2]) 
+0

这正是我所需要的,谢谢。 – Waitkus

+0

如果我想写入行[2]而不是第一行,我将如何编辑命令以更改写入的位置。 – Waitkus

+0

@Waitkus你将不得不包含两个空白列,例如'[“”,“”,location2]' – jonrsharpe

相关问题