python for file在文件结束前完成

时间:2014-12-12 11:42:32

标签: python

我正在使用以下脚本解析一些文本文件(Cisco交换机显示版本文件)。它工作正常,只是它只选择'序列号'和& “模型”行一次,并且此信息不止一行。如何让脚本继续解析整个文件?

import os
import csv

inventoryfile = open('inventory.csv', 'a')
write_inventory = csv.writer(inventoryfile)
#write_inventory.writerow( ('Hostname', 'Model', 'Serial Number') )

def parse_files(path):
    for filename in os.listdir(path):
        with open(os.path.join(path,filename),'r') as showfile:
                for line in showfile:
#                   i = 0
#                   while i < 4:
                        if '#sh' in line:
                            hostname = line.split('#')[0]
                        if 'Model number' in line:
                            model = line.split()[-1]
                        if 'System serial number' in line:
                            serial = line.split()[-1]
                        elif 'Model Number' in line:
                            model = line.split()[-1]
                        elif 'System Serial Number' in line:
                            serial = line.split()[-1]
#                       i += 1
                write_inventory.writerow( (hostname, model, serial) )


directory = raw_input("Please specify Show Files directory: ")

parse_files(directory)

3 个答案:

答案 0 :(得分:2)

您每个文件写一次而不是每行写一次,因此它只会写最后一行。将write_inventory置于for循环

答案 1 :(得分:1)

你怎么知道它只获得一次这些线?您只有一个变量序列来存储它们。每次找到相关行时,它将用最新值覆盖该变量。

如果要记录这些行的所有实例,则应将它们保存在列表中。

答案 2 :(得分:0)

如果您不明白他们的意思,请尝试以下代码:

import os
import csv

inventoryfile = open('inventory.csv', 'a')
write_inventory = csv.writer(inventoryfile)
#write_inventory.writerow( ('Hostname', 'Model', 'Serial Number') )

def parse_files(path):
    for filename in os.listdir(path):
        with open(os.path.join(path,filename),'r') as showfile:
                for line in showfile:
#                   i = 0
#                   while i < 4:
                        hostname = model = serial = ''
                        if '#sh' in line:
                            hostname = line.split('#')[0]
                        if 'Model number' in line:
                            model = line.split()[-1]
                        if 'System serial number' in line:
                            serial = line.split()[-1]
                        elif 'Model Number' in line:
                            model = line.split()[-1]
                        elif 'System Serial Number' in line:
                            serial = line.split()[-1]
#                       i += 1
                        write_inventory.writerow( (hostname, model, serial) )


directory = raw_input("Please specify Show Files directory: ")

parse_files(directory)