Python working with files

Importing os

To be able to use python for files and folders creating or deleting, we must import os module. The syntax is ” import os

Current working directory

Let’s start looking at current working directory is the directory you are at, it is referred to as cwd and is equivalent to Linux pwd. In this example, we will print the current working directory.

#WORKING WITH FILES

import os
print(os.getcwd())

#Output will be:
/Users/sam/TEST_SCRIPTS

Creating directories

Very often, we will need to create folders and directories to save our output from a script. This could be a script fetching and saving configs or output from show commands.

In below example, we create a directory called TEST_LAB1, for this we use mkdir.

import os

#Create new directory
os.mkdir("TEST_LAB1")

Changing directory path

Following up on the previous  example, let’s change path top the new created directory. For this, we use chdir, for change directory

Please note, I am using a Mac machine, so your path syntax will be different o a windows machine.

import os

#change path to newly created directory
os.chdir("/Users/sam/TEST_LAB1")

Listing directory content

To list the content of a folder or directory, we use litsdir. See below example where I list the content of the current working folder.
Note how the content is printed as a python list.

import os
print(os.listdir()))

#Output
['.DS_Store', 'sam_lab', 'test1.py', 'lists_lab.py']

Writing a file

In this example, we create a new file and write to it.
New file is “my_devices.txt” and lists R1, R3 and R3 as my nodes.

Note, that since I did not specify a path change, the file will be created in the current working directory.

f = open("my_devices.txt", "w")
f.write('R1 R2 R3')
f.close()

f = open("my_devices.txt", "r")
print(f.read())

#Output
R1 R2 R3

Python crash course video

To learn more about Python for Engineers, watch this 1hr crash course video.
This course covers foundation topics:

  • Installing Python

  • Starting on Visual Studio Code

  • Hello World

  • Variables

  • Print and formatting

  • Built-IN method

  • Lists

  • Dictionaries

  • Working with files

  • Functions

  • Conditionals & Loops

  • Interacting with network devices