Python CSV解析并打印到stdout的新行

时间:2013-11-12 02:52:07

标签: python csv

我有一个包含三列的CSV文件。第三列“row [02]”有一个IP列表,其中包含以逗号分隔的IP列表。我想转向以下内容:

  

“column01”,“column02”,“192.168.1.1,192.168.2.1,192.168.3.1”

进入(减去子弹):

  
      
  • column01,column02,192.168.1.1
  •   
  • column01,column02,192.168.2.1
  •   
  • column01,column02,192.168.3.1
  •   

提供了我的代码,但输出仍然显示以下内容:

  

row01,row02,192.168.1.1,192.168.2.1,192.168.3.1

如果需要任何其他信息,请告诉我。提前谢谢。

原始代码:

#!/usr/bin/python
import csv, sys, time, logging

s = time.strftime('%Y%m%d%H%M%S')

# Create exception file from standard output
class Logger(object):
    def __init__(self):
        self.terminal = sys.stdout
        self.log = open((s) + "_" + sys.argv[1], "a")

    def write(self, message):
        self.terminal.write(message)
        self.log.write(message) 

def main():
    # Start screen capture to output into CSV file
    sys.stdout = Logger()

    # File input argument
    with open(sys.argv[1], "rb") as f:
        reader = csv.reader(f, delimiter=',')
        for row in reader:
            print row[0], ",", row[1], ",", row[2]

if __name__=='__main__':
    main()

更新代码:

#!/usr/bin/python
import csv, sys, time, logging

s = time.strftime('%Y%m%d%H%M%S')

# Create exception file from standard output
class Logger(object):
    def __init__(self):
        self.terminal = sys.stdout
        self.log = open((s) + "_" + sys.argv[1], "a")

    def write(self, message):
        self.terminal.write(message)
        self.log.write(message) 

def main():
    # Start screen capture to output file
    sys.stdout = Logger()

# File input argument
with open(sys.argv[1], "rb") as f:
    reader = csv.reader(f, delimiter=',', skipinitialspace=True)
    for row in reader:
        network = row[0].replace(" ","")
        network_group = row[1].replace(" ","")
        address = row[2].replace(',','\n').replace(" ","")
        if "-" in address: #parse network ranges
            try:
                print IP(address), network, network_group
            except:
                netrange = address.replace('-'," ").replace(" ",",")
                print netrange, ",", network, ",", network_group
        else:
            print address, ",", network, ",", network_group

if __name__=='__main__':
    main()

1 个答案:

答案 0 :(得分:4)

打印它的原因是:

row01, row02, 192.168.1.1, 192.168.2.1, 192.168.3.1

您是否要求它为每一行做到这一点:

for row in reader:
    print row[0], ",", row[1], ",", row[2]

如果你想要它做一些不同的事情,你必须告诉它做一些不同的事情。它无法读懂你的想法。因此,如果您想(例如,在逗号上拆分row[2],则需要编写一些代码来执行此操作。像这样:

for row in reader:
    addresses = row[2].split(", ")
    for address in addresses:
        print row[0], ",", row[1], ",", address