从一个csv获取输入并写入另一个csv [英] Take input from one csv and write to a second csv

查看:82
本文介绍了从一个csv获取输入并写入另一个csv的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从一个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

我已经尝试了第二部分的一些选项,但是在正确编写时遇到了麻烦.上面的代码获取了正确的输出,但是每个单元格只写了一个字母.我尝试了其他选择,但无所适从.

解决方案

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆