7 - Working With Files
7 - Working With Files
When working with network equipment (and not only), files can be:
• configurations (simple, non-structured text files)
• configuration templates: usually a special file format (the use of Jinja2 to create
configuration templates).
• files with connection options: usually they are structured files in some particular
format: YAML, JSON, CSV.
• other Python scripts: working with modules
This section covers simple text files. For example, Cisco configuration file.
File opening
To start working with a file you have to open it.
open
Function open is most often used to open files:
file = open('file_name.txt', 'r')
Function open creates a file object to which different methods can then be applied to work
with it.
38
File reading
Python has several file reading methods:
• read - reads the contents of file to string
• readline - reads file line by line
• readlines - reads file lines and creates a list from the lines
Let’s see how to read contents of files using the example of r1.txt:
!
service password-encryption
service sequence-numbers
!
no ip domain lookup
!
ip ssh version 2 !
read
Method read reads the entire file to one string:
f = open('r1.txt')
f.read()
# '!\nservice password-encryption\ ,\nservice
sequence-numbers\n!\nno ip domain lookup\n!\nip ssh version
2\n!\n'
f.read()
# ''
When reading a file once again an empty line is displayed. This is because the whole file is
read when read method is called. And after the file has been read the cursor stays at the
end of file. The cursor position can be controlled by seek method.
readline
File can be read line by line using readline method:
f = open('r1.txt')
for line in f:
print(line)
readlines
Another useful method is readlines. It reads file lines to the list:
39
f = open('r1.txt')
f.readlines()
# ['!\n',
'service password-encryption\n',
'service sequence-numbers\n',
'!\n', 'no ip domain lookup\n',
'!\n',
'ip ssh version 2\n',
'!\n']
If you want to get lines of a file but without a new line character at the end, you can use
split method and specify symbol \n as a separator:
f = open('r1.txt')
f.read().split('\n')
seek
Until now, file had to be reopened to read it again. This is because after reading methods a
cursor is at the end of the file. And second reading returns an empty string.
To read information from a file again you need to use the seek method which moves the
cursor to the desired position.
f.seek(0)
# with seek method you can go to the beginning of file (0 means
the beginning of file)
File writing
When writing information to a file, it is very important to specify the correct mode for
opening the file, so as not to accidentally delete it:
• w - open file for writing. If file exists, its content is removed
• a - open file to add data. Data is appended to the end of the file
40
write
Method write expects string to write.
cfg_lines = ['!',
'no ip domain lookup',
'!',
'ip ssh version 2',
'!']
writelines
Method writelines expects list of strings as an argument.
cfg_lines = ['!',
'no ip domain lookup',
'!',
'ip ssh version 2',
'!']
f = open('r2.txt', 'w')
f.writelines(cfg_lines)
f.close()
41
with statement
The with statement is called the context manager.
Python has a more convenient way of working with files than the ones used so far -
statement with:
with open('r1.txt', 'r') as f:
for line in f:
print(line)
42
Tasks
Task 7.1 :
Process the lines from the ospf.txt file and print information for each line in this form to
the stdout:
Prefix 10.0.24.0/24
AD/Metric 110/41
Next-Hop 10.0.13.3
Last update 3d18h
Outbound Interface FastEthernet0/0
Task 7.2 :
Create a script that will process the config_sw1.txt configuration file. The filename is
passed as an argument to the script.
The script should return to the stdout commands from the passed configuration file,
excluding lines that start with ‘!’.
Task 7.2a :
Make a copy of the code from the task 7.2.
Add this functionality: The script should not print to the stdout commands, which contain
words from the ignore list. The script should also not print lines that begin with !.
Check the script on the config_sw1.txt configuration file. The filename is passed as an
argument to the script.
ignore = ["duplex", "alias", "Current configuration"]
43
Task 7.2b :
Make a copy of the code from the task 7.2a. Add this functionality: instead of printing to
stdout, the script should write the resulting lines to a file.
In this case, the lines that are contained in the ignore list and lines that start with ! must be
filtered.
ignore = ["duplex", "alias", "Current configuration"]
44