我从一个csv中提取数据并获得2个不同的变量,这些变量是不同格式的位置,一个用于单个楼层,另一个用于多个楼层。我的代码拉取数据按预期工作,我在第二个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
我已经尝试了第二部分的一些选项,并且正在编写正确的麻烦。以上输出正确但每个单元格写一个字母。我尝试了其他选择,但我不知所措。
答案 0 :(得分:2)
writerow
期望一个可迭代的,并且字符串是逐个字符的迭代。试试:
writer.writerow([location2])