Table of Contents

Files and Directories

Directories - Navigation, Modification and beyond

Python is an interpreter as well as a programming language. Python translates the commands typed in to interpret to a machine readable format to run against the target. For Python to interact with the host to navigate through directories and manipulate them and more Python will need to use the inbuilt
module. The module must first be imported into the runtime environment (known as the existing open session of your python instance) using the

The OS module in python provides functions for interacting with the operating system. OS, comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality. The
modules include many functions to interact with the file system.

To run any of the below commands first import the
module. by typing

>>>import os

To find the current Directory you are working with type
>>>os.getcwd() ''C:\\WINDOWS\\system32''

To list directories use the os method os.listdir()

Nesting directories

To change the directory use os.chdir(path) where path is substituted for the target location

e.g. To change to another windows directory use

Or to move up a directory

To make a directory type

Start by changing to your desktop directory to find the files we will be creating easier And to delete them.


To remove file/directory
Note the below options will delete the file from the system and will not be recoverable by default.
will remove a file.
will remove an empty directory.
will delete a directory and all its contents.

Create a New File

To create a new file in Python, use the open() method, with one of the following parameters:
"x" - Create - will create a file, returns an error if the file exist
"a" - Append - will create a file if the specified file does not exist
"w" - Write - will create a file if the specified file does not exist

Mode Description
'r' This is the default mode. It Opens file for reading.
'w' This Mode Opens file for writing. If file does not exist, it creates a new file. If file exists it truncates the file.
'x' Creates a new file. If file already exists, the operation fails.
'a' Open file in append mode. If file does not exist, it creates a new file.
't' This is the default mode. It opens in text mode.
'b' This opens in binary mode.
'+' This will open a file for reading and writing (updating) /td>

This creates a new python file on our desktop.

>>>txt_object.write("This adds text to file")
.write method writes text to file

closes the file to stop further amendments thus saving the newly created file.

To then read the contents of the file to the shell host output
>>> txtfile_objectput=open("", "r") >>> print(

To add new lines to the file then reopen again

Then write
>>>txt_object.write("Foo Foo Foobar")
Then close again

To find all environmental variables type