File Handling Cheat Sheet in Python

File Handling

File handling in Python requires no importing of modules.

File Object

Instead, we can use the built-in object “file”.

That object provides basic functions and methods necessary to manipulate files
by default.

Before you can read, append or write to a file, you will first have to it using
Python’s built-in open() function.

In this post I will describe how to use the different methods of the file object.


The open() function is used to open files in our system, the filename is the
name of the file to be opened.

The mode indicates  how the file is going to be opened “r” for reading,
“w” for writing and “a” for an appending.

The open function takes two arguments, the name of the file and  the mode
for which we would like to open the file.

By default, when only the filename is passed, the open function opens the file
in read mode.


This small script, will open the (hello.txt) and print the content.

This will store the file information in the file object “filename”.

ilename = "hello.txt"
file = open(filename, "r")
for line in file:
print line,

Read ()

The read functions contains different methods, read(),readline() and readlines()

read() #return one big string

readline #return one line at a time

readlines #returns a list of lines

Write ()

This method writes a sequence of strings to the file.

write () #Used to write a fixed sequence of characters to a file

writelines() #writelines can write a list of strings.

Append ()

The append function is used to append to the file instead of overwriting it.

To append to an existing file, simply open the file in append mode (“a”):


When you’re done with a file, use close() to close it and free up any system
resources taken up by the open file

File Handling Examples

Let’s see some examples

To open a text file, use:

fh = open("hello.txt", "r")

To read a text file, use:

fh = open("hello.txt","r")

To read one line at a time, use:

fh = open("hello".txt", "r")
print fh.readline()
To read a list of lines use:
fh = open("hello.txt.", "r")
print fh.readlines()


To write to a file, use:

fh = open("hello.txt","w")
write("Hello World")

To write to a file, use:

fh = open("hello.txt", "w")
lines_of_text = ["a line of text", "another line of text", "a third line"]

To append to file, use:

fh = open("Hello.txt", "a")
write("Hello World again")

To close a file, use

fh = open("hello.txt", "r")


Must Read :- Top 10 Useful Python Tricks For Beginners

Bypass Online CAPTCHA Using Python Language