I'm starting a python script to parse a number of small text files in a folder. I need to retrieve particular information that will always be different (in this case hostname, model & serial number for a Cisco switch) and so can't use a regular expression. However I can easily find the line that contains the information. This is what I have so far:
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
This, however, is returning:
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'
where 'Switch01-run.txt' is a file in the specified folder. I can't figure out where I'm taking a wrong turn.
The problem is that os.listdir()
is returning the filenames from the directory, not the complete path to the file.
You need to do this instead:
with open(os.path.join(path,filename),'r') as showfile:
This fixes two issues - the IOerror, and the error you will get trying to read lines from a string.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.