Skip to content

Working with files

See content for switch.cfg

Reading a file

Show help for open(). Discuss input arguments (file and mode)

help(open)

Open a file:

config = open('switch.cfg')
type(config)
dir(config)

Read the file:

content = config.read()
print(content)

Read the file again to show that now the content is empty, this is because you have removed it from the buffer or exhausted it.

content = config.read()
print(content)

Close the file:

config.close()

Writing to a file

Use the following dictionary:

vlans = [
    {'id': '10', 'name': 'USERS'},
    {'id': '20', 'name': 'VOICE'},
    {'id': '30', 'name': 'WLAN'},
    {'id': '40', 'name': 'APP'},
    {'id': '50', 'name': 'WEB'}
]

Print the dictionary with json:

import json
content = json.dumps(vlans, indent=4)
print(content)

Open a file for writing:

vlans_file = open('vlans.cfg', 'w')

Show that the file was created.

Write to a file:

vlans_file.write(content)

Show that the file is still empty.

Close the file:

vlans_file.close()

Show the file that there is a content now.

The with statement

Open the file with the with statement:

with open('switch.cfg`) as f:
    content = f.read()
print(content)