0

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

“column01”、“column02”、“192.168.1.1、192.168.2.1、192.168.3.1”

进入(减去项目符号):

  • 01 列,02 列,192.168.1.1
  • 列01,列02,192.168.2.1
  • 列01,列02,192.168.3.1

提供的是我的代码,但输出一直显示以下内容:

第01行、第02行、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()
4

1 回答 1

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
于 2013-11-12T02:55:38.103 回答