[go: up one dir, main page]

0% found this document useful (0 votes)
11 views7 pages

7 - Working With Files

Uploaded by

fersd2018
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views7 pages

7 - Working With Files

Uploaded by

fersd2018
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

7.

Working with files


In real life, in order to make full use of everything covered before this section you need to
understand how to work 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.

There are several aspects to working with files:


• opening/closing
• reading
• writing

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.

File opening modes:


• r - open file in read-only mode (default)
• r+ - open file for reading and writing
• w - open file for writing only
• if file exists, its content is removed
• if file does not exist, a new one is created
• w+ - open file for reading and writing
• if file exists, its content is removed
• if file does not exist, a new one is created
• a - open file to add a data. Data is added to the end of file
• a+ - open file for reading and writing. Data is added to the end of file

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

Both modes create a file if it does not exist.

The following methods are used to write to a file:


• write - write one line to file
• writelines - allows to send as argument a list of strings

40
write
Method write expects string to write.
cfg_lines = ['!',
'no ip domain lookup',
'!',
'ip ssh version 2',
'!']

f = open('r2.txt', 'w') # Open r2.txt file in write mode

# Convert the list of commands to one large string using join


cfg_lines_as_string = '\n'.join(cfg_lines)
f.write(cfg_lines_as_string) # Write a string to a file

f.write('\nhostname r2') # you can add a string manually

f.close() # file should be closed

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)

In addition, statement with guarantees file closure automatically. (use


print(line.rstrip()) to get get rid of extra empty lines)

Open two files


Sometimes you have to work with two files simultaneously. Example:
with open('r1.txt') as src, open('result.txt', 'w') as dest:
for line in src:
if line.startswith('service'):
dest.write(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 ‘!’.

There should be no blank lines in the output. Output example:


$ python task_7_2.py config_sw1.txt
Current configuration : 2033 bytes
version 15.0
service timestamps debug datetime msec
service timestamps log datetime msec
no service password-encryption
hostname sw1
interface Ethernet0/0
...

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.

File names must be passed as arguments to the script:


1. name of the source configuration file
2. name of the destination configuration 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

You might also like