从一个csv获取输入并写入另一个csv [英] Take input from one csv and write to a second 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
我已经尝试了第二部分的一些选项,但是在正确编写时遇到了麻烦.上面的代码获取了正确的输出,但是每个单元格只写了一个字母.我尝试了其他选择,但无所适从.
writerow
期望可迭代,并且字符串逐个字符地迭代.试试:
writer.writerow([location2])
i am pulling data from one csv and get 2 different variables that are location in different formats one is for a single floor and the other is for multiple floors. my code to pull the data works as expected, i am having troubles writing to the correct rows in the second csv, the data is writing but it is doing this letter by letter.
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
I have tried a few options for the second part and am having troubles writing correctly. The above takes the correct output but writes it a single letter per cell. I have tried other options but am at a loss.
writerow
expects an iterable, and strings are iterated character-by-character. Try :
writer.writerow([location2])
这篇关于从一个csv获取输入并写入另一个csv的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!