我正在启动一个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'
开关01在哪里-运行.txt'是指定文件夹中的文件。我不知道我在哪里拐错了弯。你知道吗
问题是
os.listdir()
返回的是目录中的文件名,而不是文件的完整路径。你知道吗您需要这样做:
这修复了两个问题-IOerror和尝试从字符串中读取行时会遇到的错误。你知道吗
相关问题 更多 >
编程相关推荐