IOError:[Errno 2]用于解析txt文件的Python脚本

时间:2014-12-11 13:53:45

标签: python

我正在启动一个python脚本来解析文件夹中的一些小文本文件。我需要检索始终不同的特定信息(在这种情况下,Cisco交换机的主机名,型号和序列号),因此不能使用正则表达式。但是我可以很容易地找到包含信息的行。这就是我到目前为止所做的:

import os

def parse_files(path):
    for filename in os.listdir(path):
        with open(filename,'r').read() as showfile:
            for line in showfile:
                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]
        showfile.close()

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

parse_files(path)

print hostname,model,serial

然而,这回来了:

Traceback (most recent call last):
  File "inventory.py", line 17, in <module>
    parse_files(path)
  File "inventory.py", line 5, in parse_files
    with open(filename,'r').read() as showfile:
IOError: [Errno 2] No such file or directory: 'Switch01-run.txt'

其中'Switch01-run.txt'是指定文件夹中的文件。我无法弄清楚我在哪里走错了路。

1 个答案:

答案 0 :(得分:1)

问题是os.listdir()正在从目录返回文件名,而不是文件的完整路径。

你需要这样做:

with open(os.path.join(path,filename),'r') as showfile:

这解决了两个问题 - IOerror,以及尝试从字符串中读取行的错误。