Python文本文件到.csv

时间:2014-01-21 00:50:42

标签: python python-3.x

首先,感谢您阅读我的帖子。从.txt文件解析数据并将其放入.csv文件时,我遇到了一个特殊问题。从文本文档我试图从路由器配置文件中绘制主机名和环回地址,然后将其放在Excel工作表的单独列中。相反,当我添加“outFile.write(”“。join(buffer))”时,它在excel表中是一个混乱的混乱,它还添加了打印功能没有的字符串。

以下是代码:

inFile = open("Data.txt")
outFile = open("result.csv", "w")
buffer = []
keepCurrentSet = True
for line in inFile:
        buffer.append(line)
        if line.startswith ("hostname"):
                print (line) 
                outFile.write("".join(buffer))
        elif line.startswith("interface Loopback"):
                print (line)
                print (next(inFile))
                outFile.write("".join(buffer))
inFile.close()
outFile.close()

这是文本文件

[spoiler]
version 12.4
service timestamps debug datetime msec
service timestamps log datetime msec
no service password-encryption
!
hostname cisco1841
!
boot-start-marker
boot-end-marker
!
logging buffered 51200 warnings
!
no aaa new-model
clock timezone Arizona -7
ip cef
!
!
no ip dhcp use vrf connected
!
ip dhcp excluded-address 10.10.1.1
ip dhcp excluded-address 10.10.3.1
!
ip dhcp pool Inside
network 10.10.1.0 255.255.255.0
dns-server 205.171.3.65 4.2.2.1
default-router 10.10.1.1
!
ip dhcp pool Wireless
import all
network 10.10.3.0 255.255.255.0
dns-server 205.171.3.65 4.2.2.1
default-router 10.10.3.1
lease 3
!
!
multilink bundle-name authenticated
!
!
!
!
username xxxxxxx privilege 15 secret 5 xxxxxxxxxx
!
bridge irb
!
!
!
interface Loopback0
ip address 10.10.0.1 255.255.255.255
!
interface FastEthernet0/0
description Inside LAN
ip address 10.10.1.1 255.255.255.0
ip nat inside
duplex auto
speed auto
[/spoiler]

2 个答案:

答案 0 :(得分:0)

buffer = []

buffer是一个列表。对于原始文件中的每一行,您都附加到它:

for line in inFile:
    buffer.append(line)

因此它将始终包含已读取的所有行的列表。

outFile.write("".join(buffer))

然后,每次找到相关行时,都会将整个buffer写入文件。但是因为buffer是读取的所有行的列表,所以基本上重复地将所有先前读取的行的串联写入文件。

你应该写下这一行:

outFile.write(line)

您无需在此处推进文件迭代器:print (next(inFile))。 for循环已经这样做了。

如果您进行了这些更改,脚本将过滤以"hostname""interface Loopback"开头的行。根本不需要buffer。如果您确实想要"interface Loopback"之后的行,那么您应该替换

print (next(inFile))

line = next(inFile)

然而,这似乎不是你想要的。我不知道你想做什么。

所以我的猜测是你想把主机名和IP地址分成两列,然后可能会迭代很多文件。在这种情况下,您可以读取整个文件(假设它不是太长)并使用正则表达式来过滤您需要的内容。然后,您可以在csv

的帮助下编写结果
import csv
import re

outFile = open("result.csv", "w")
outFileCsv = csv.writer(outFile)
outFileCsv.writerow(["hostname", "loopback ip"])

for filename in ["Data.txt"]: # Add more files here
    try:
        inFile = open(filename).read()
    except IOError:
        print("Could not read {0}".format(filename))
        continue
    try:
        hostname = re.search("\nhostname (.*)\n", inFile).group(1)
        loopback_ip = re.search("\ninterface Loopback.*\n(?!\ninterface).*ip address ([0-9\\.]*)", inFile).group(1)
    except AttributeError:
        print("No match in {0}".format(filename))
        continue    
    outFileCsv.writerow([hostname, loopback_ip])

outFile.close()

答案 1 :(得分:0)

如果您尝试在Excel中打开.csv,那么它可能不会非常易读。 csv代表逗号分隔值,你的输出没有逗号,但很多空格和换行符 - excel实际上不能指望它们处理。以下是您的程序输出(加上换行符):

hostname cisco1841

interface Loopback0

ip address 10.10.0.1 255.255.255.255

您可以通过在输出文件中添加逗号代替已存在的空格来更正确地格式化输出。对于你想要抓取的ip地址行,它更难,因为它的名字也有一个空格。我通过抓住该行中列出的第一个ipAddress解决了这个问题 - 如果你想要另一个或两者都是一个简单的解决方案。我还删除了你正在使用的缓冲区和“keepCurrentResultSet”,因为我真的不需要它们。

inFile = open("text.txt")
outFile = open("result.csv", "w")
for line in inFile:
        if line.startswith ("hostname"):
                outFile.write(line.replace(' ',','))
        elif line.startswith("interface Loopback"):
                outFile.write(line.replace(' ',','))
                ipAddrLine = next(inFile)
                ipAddress = ipAddrLine.split(' ')[2:3]
                outFile.write('ip address,' + ','.join(ipAddress))
inFile.close()
outFile.close()

这给出了这个输出,它应该被认为是有效的.csv格式由excel:

hostname,cisco1841
interface,Loopback0
ip address,10.10.0.1
相关问题