Working with Files and Directories in Python

Ayush Dixit
Nerd For Tech
Published in
3 min readJan 4, 2022

Python makes it very easy to work with files on the fly. Here i’m listing out some of the most frequently used python built-in modules and functions for handling files.

Reading a file

Method 1 :

file = open("my_file.txt")
contents = file.read()
print(contents)
file.close()

Method 2 :

with open("my_file.txt") as file:
contents = file.read()
print(contents)

The second method in which we have used with open(…) as …” Pattern. The ‘with’ keyword is used when working with unmanaged resources such as file streams.

In method 1 we are explicitly closing the file after reading it. However, the ‘with’ keyword itself takes care of the ‘exit()’ method.

To save Processing time we use 'with'. No need to close the file by giving file.close(). ‘With’ automatically closes the file

Writing to a File

By default the mode of the open keyword is ‘read’ only. To write we need to use ‘write’ mode.

Caution : It will delete the old content in the file and replaces it with the new content specified.

with open("my_file.txt", mode ="w") as file:
file.write("New Text.")

Appending to a File

SImilarly, for appending to a file we change the mode to “a” instead of “w”. The old content in the file remains intact while the new content specified gets appended or added onto the file alongwith the old content.

with open("my_file.txt", mode ="a") as file:
file.write("\nAppended content")

Creating a new File

The ‘with’ keyword is a multipurpose keyword when it comes to working with files. It automatically creates a new file if the file doesn’t exist already.

with open("code_with_ayush.txt", mode = "w") as file:
file.write("new text")

Deleting a file

To delete a file we first import the OS module. The OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules.

import os

delete_this_file = '<path of the file>'
os.remove(delete_this_file)

Working with Directories

Get the current path

import os
print(os.getcwd())

os.getcwd() → fetches the current directory

Make a new directory

os.mkdir("new_dir")

os.mkdir → makes a new directory

Change Directory

os.chdir("new_dir")

Create a new file inside a directory

open('index.html', 'x')

“x” is similar to “w”. But for “x”, if the file exists, raise FileExistsError. For “w”, it will simply create a new file / truncate the existed file.

To go one step pack in the path hierarchy

os.chdir("../new_dir")

List the contents of the directory

os.listdir("new_dir/website")

listdir → method lists all the contents inside the directory

Check whether content is a subdirectory or a file

for name in os.listdir(dir):
fullname = os.path.join(dir,name)
if os.path.isdir(fullname):
print(f"{fullname} is a directory")
else:
print(f"{fullname} is a file")

os.path.join() method in Python join one or more path components intelligently.

Fetching the absolute path

def parent_directory():

# Create a relative path to the parent
# of the current working directory
relative_parent = os.path.join(os.getcwd(), os.pardir)
# Return the absolute path of the parent directory
return os.path.abspath(relative_parent)

print(parent_directory())

To know more about the os.path.join() method. I would recommend this article which i found immensely helpful.

Moving Files and Directories

>>> import shutil
>>> shutil.move('ayush/', 'code/')
'code'

shutil.move('ayush/', 'code/') moves ayush/ into code/ if code/ exists. If code/ does not exist, ayush/ will be renamed to code

Renaming Files and Directories

os.rename('text.html', 'write.html')

The line above will rename text.html to write.html. If the destination path points to a directory, it will raise an OSError.

Did you like my efforts? If Yes, please follow me to get my latest posts and updates or better still, buy me a coffee!☕

--

--

Ayush Dixit
Nerd For Tech

Hi, I’m a postgraduate from IIT-Indore(M.Tech). Specialization in Comm. Signal Processing and Machine Learning/AI. Presently working as an Engineer in Qualcomm.