File Handling: Exercise: Create A Folder Named Myfiles. in The Folder, Using Notepad or Any Other Text Editor
File Handling: Exercise: Create A Folder Named Myfiles. in The Folder, Using Notepad or Any Other Text Editor
File Handling
A file is a named location on the memory containing a sequence of bytes. File Handling may be
useful in permanently storing data or information generated by a program, which would
otherwise be unavailable after the program has finished running, since they are only stored
temporarily in the volatile RAM. Luckily, Python has the capability to access your device file
system using the io module. However, being the default module for handling I/O functions,
you do not need to literally import the io module or any other module, while handling files.
Exercise: Create a folder named MyFiles. In the folder, using Notepad or any other text editor,
create a text file (with the .txt file extension), and type in Hello World. Name the file Hello.txt.
It is possible to create a text file using WPS Office. Simply click on the + button, and click New
Memo from the list of options, then save your file in the said location with the .txt extension.
Ensure the .txt extension is not repeated in your file name.
Now, in the same folder, create a python program of any name of your choice, and write the
following code:
MyHello = open("Hello.txt", "r")
x = MyHello.read()
print(x)
1 |B e y on d P a p e r s
BeyondPapers Workshop 1.0 (Launch into Python Programming)
What has just happened? With Python we have just accessed the file Hello.txt and read its
content! How did we do that? First we need to open the file in question.
Opening a File
To open a file, use the open() function. The open() function creates a file object (or stream),
and the variable to which the it is assigned to becomes the file handler for the file on the
operating system. The open() function takes two arguments. The syntax is:
open(file, mode)
file refers to the address of the file to be handled. If the file to be opened is located on the
same directory as the program opening it, it may be enough to write just the name (with the
file extension, for example, "home.html" or "Hello.txt"). However, if the file is located
elsewhere, you may need to specify the proper relative path or an absolute path.
mode refers to the way we want to open the file, and what actions can be done on the file. In
other words, it defines the behaviour of the file handler, and what methods can be used on it.
In the above example, Hello.txt is the file (or address of the file) to be opened, and r
represents the mode with which we want to open the file. Opening a file with the r mode
means we want to open the file for reading. The open() function therefore returns a read-only
file object representing the file on the disk, and as such we cannot write to or edit the file. This
is the default mode, which means, we could have opened the file as:
open("Hello.txt")
There are other modes with which we can open a file. Below is a list of all the modes:
Mode Purpose Behaviour
r for reading content only This is default.
You cannot edit the file.
w for writing new content only Creates a new file.
Overwrites, if a file with the same name
already exists. (Clears initial contents.)
a for appending (or writing more) content Creates a new file, if the file does not
only exist.
x for creating and writing to files Raises an exception if the file already
exists.
2 |B e y on d P a p e r s
BeyondPapers Workshop 1.0 (Launch into Python Programming)
r+ for reading and writing Raises an exception if the file does not
exist.
w+ For reading and writing Creates a new file.
Overwrites, if a file with the same name
already exists. (Clears initial contents.)
a+ For reading and appending Creates a new file, if the file does not
exist.
x+ For creating, writing and reading Raises an exception if the file already
exists.
In Python, files can be handled in either text or binary formats. To specify which format you
want to work with, you add "t" (text) or "b" (binary) to the mode. The default is "t".
open("Hello.txt") therefore means open("Hello.txt", "rt"). If for example, a file is to be opened
as read and write in binary format, the mode will be written as "rb+" or "wb+".
Closing a File
It is a good practice to close files, after all operations have been carried out on the file. Closing
a file will free up resources that were tied to the file, including memory, battery life etc.
Sometimes, due to buffering, certain changes made to a file may not be shown, until the file
handler is closed.
MyHello.close()
The with statement can also be used to close a file. It automatically closes the file when the
block of code is finished executing. We do not need to explicitly call the close() method.
with open("Hello.txt") as f:
content = f.read()
print(content)
The file is automatically closed after all codes for working on the file in the with statement
have been executed.
3 |B e y on d P a p e r s
BeyondPapers Workshop 1.0 (Launch into Python Programming)
Reading a File
To read the contents of a file, use the read() method.
Exercise: Create a file, MyLines.txt. Write the following in it, and save:
To read the contents of MyLines.txt, write a program with the following code, in the same
folder:
File = open("MyLines.txt")
Lines = File.read()
print(Lines)
File.close()
When opening a file for reading, if the file to be read does not exist, an exception will be
raised.
The read() method reads the whole content of a file. The read() method can also take an
argument n, used to read only parts of a file. It tells the file handler to return only the first n
bytes or characters. If a negative value is given, it will return the rest of the file content.
File = open("MyLines.txt")
Lines = File.read(12)
print(Lines) # Prints "BeyondPapers"
File.close()
4 |B e y on d P a p e r s
BeyondPapers Workshop 1.0 (Launch into Python Programming)
Lines are separated by the line break \n character. To read the lines of a file one after the
other, use the readline() method. The readline() method can also take an argument n, to read
the first n characters from the line. A negative value of n returns the whole line.
# To read the first two lines of MyLines.txt, apply the readline() method twice.
File = open("MyLines.txt")
Line1 = File.readline()
print(Line1)
Line2 = File.readline()
print(Line2)
Line3 = File.readline(4)
print(Line3)
File.close()
Output is:
BeyondPapers Workshop 1.0 hosts training in Python Programming.
It’s
>>>
The readline() method, reads each line of a file one at a time, and appends the line break \n
character to each line (except the last line). This implies that we can actually loop through the
whole lines of the file:
File = open("MyLines.txt")
while True:
Line = File.readline()
if len(Line) > 0: print(Line)
else: break
5 |B e y on d P a p e r s
BeyondPapers Workshop 1.0 (Launch into Python Programming)
File.close()
While both gives the same result, it may be more economical to write:
File = open("MyLines.txt")
for i in File: print(i)
File.close()
The readlines() method can be used to return a list of the lines instead. When the argument n
is passed, the readline() method returns the lines up to the next complete line after n
characters. When a negative n is supplied, the whole lines are read.
File = open("MyLines.txt")
AllLines = File.readlines()
print(AllLines)
File.close()
Writing to a File
Just like files can be read, files can as well be written to. This is done by opening a file as a
writable file and then using the write() method on it. To open a writable file, open it with the
w mode. Opening a file with "w" overwrites any previous file with the same name in the
directory – that is it deletes the contents of the file, leaving it empty, until it is written to.
Here we will be creating a new file, LetsWrite.txt, and writing some content to it.
x = open("LetsWrite.txt", "w")
x = open("LetsWrite.txt", "r")
print(x.read()) # Prints # "Something has been written to me!"
x.close()
e = open("StudentEmails.txt", "r")
print(e.read())
e.close()
Appending a File
When you append a file, you write more contents to it, without altering the initial content. To
append a file, open it in the append mode (that is, with mode "a"), and write your contents to
it. Opening a file with mode "a" creates a new file, if it does not already exist.
# Let's assume I have earlier written some content to my Notebook, or it already has some.
7 |B e y on d P a p e r s
BeyondPapers Workshop 1.0 (Launch into Python Programming)
You can for example use the append mode to append the items of a list to a file:
# My teacher writes this on the board:
Note = open("Notebook.txt", "a") # I opened it in append mode to avoid losing my old notes.
Note.write("\n\n%s" %Topic)
for i in List:
Note.write("\n%s" %i)
Note.close() # I have to close my note, so I can free up space, and make it usable by other
programs.
MY STORE
Hacksaw
Drill
Rule
>>>
Seeking in a File
8 |B e y on d P a p e r s
BeyondPapers Workshop 1.0 (Launch into Python Programming)
Earlier in this tutorial, we used the readline() method, and observed that the file handler
automatically does not repeat line 1, when it is repeatedly used on the file object. This is
possible because the file handler uses a location pointer to ‘mark off’ its last position. When a
file is just opened in read mode, the location of the file handler is 0, and when an action, such
as read() is done on a file object, the file handler is moved to the end of the file. Attempting to
read the file once more will return a null string. Opening a file in append mode will place the
file handler at the end of the file, allowing us to write more content to the end of the file,
without altering the previous.
Sometimes, we may need to read the content of a file randomly or describe a specific position
for the file handler in a file stream. We use the seek() method to achieve this. The syntax for
the seek() method is:
seek(offset, location)
While location specifies an absolute value, offset specifies the position of a file handler relative
to location – that is, it specifies the number of bytes from or to location. For example:
# I need to recover parts of my note.
# To set the file handler 11 bytes from the beginning of the file, and read the first 5 bytes:
Note.seek(11)
print(Note.read(5))
# To set the file handler to the current position of the file handler:
# Note that nonzero offsets can not be used, when location = 1 or 2, while working with texts.
# It is only possible when the file is opened in binary mode. ("rb" for instance)
Note.seek(0, 1)
print(Note.readline())
9 |B e y on d P a p e r s
BeyondPapers Workshop 1.0 (Launch into Python Programming)
first
note.
>>>
While the seek() method returns the newly set position of the file hander, the tell() method
returns the current position of the file handler:
Note = open("Notebook.txt", "a")
# Appending mode places the file handler at the end of the file.
print(Note.tell()) # Prints 95
The seekable() method can be used to check if the seek() method can be used on a file object –
returns True or False.
Editing a File
To edit a file, simply open the file in read mode, and read it to a variable. You then perform
operations on the variable and write it back to the file. You may also loop through each line or
word separately, and edit the intended item.
The example below shows how to replace all instances of "hate" with "like":
# The above code is just to create the file MyHateList.txt, and write the intended content.
10 |B e y on d P a p e r s
BeyondPapers Workshop 1.0 (Launch into Python Programming)
# Confirm the content. We do not need to reopen the file, since we opened the file in read
and write mode.
Like.seek(0) # Returns the file handler to the beginning of the file.
print(Like.read())
Like.close()
Output is:
I HATE snakes.
I like monkeys.
I like dogs.
I like cats.
I LIKE pets.
>>>
Copying a File
To copy a file or its content, simply open the file in read mode, read the file and write it to
your new file. Here, we will be copying a file from a main directory to a sub-directory. Create a
folder named Parent, and create another folder named Child inside of Parent.
Inside Parent, create a program, and write the following:
Old = open("old.txt","w")
11 |B e y on d P a p e r s
BeyondPapers Workshop 1.0 (Launch into Python Programming)
# All we have done up there is to create the old file we want to copy
New = open("Child/new.txt", "w") # Creates a file for writing inside the folder Child.
New.write(OldContent) # Writes the old content into new.txt
New.close() # You may need to close your file, for changes to be seen.
Moving a File
The process of moving a file is similar. You just need to create both files with the same name in
different folders, and delete the old one.
Deleting a File
Python does not have a built-in method to delete files, but you can import the OS module, and
use its remove() function:
import os
os.remove("old.txt")
The remove() function will raise an exception if the file does not exist. To avoid this, check if
the file exists first:
import os
os.remove("older.txt") if os.path.exists("older.txt") else print("File not found!")
12 |B e y on d P a p e r s
BeyondPapers Workshop 1.0 (Launch into Python Programming)
To delete only the content of a file, while preserving the file itself, it is enough to open it in
write mode.
file = open("binfile.bin","wb")
s = "Hello World"
arr = s.encode("utf-8") # Encodes the string in UTF-8 characters as bytes.
13 |B e y on d P a p e r s