CMPE 30032
Module 2
File Handling in Python
Be able to read, comprehend,
trace, adapt and create Python
code that:
• Opens a file
Learning
• Reads data from a file into a
Goals/Objectives program
• Writes data from a program into a
file
• Appends data from a program into a
file
• Closes a file
What Is File?
File is a named location on disk to store related information. It is used to permanently
store data in a non-volatile memory (e.g., hard disk).
• Since Random Access Memory (RAM) is volatile which loses its data when computer
is turned off, we use files for future use of the data.
• When we want to read from or write to a file, we need to open it first. When we are
done, it needs to be closed, so that resources that are tied with the file are freed.
Hence, in Python, a file operation takes place in the following order.
1. Open a file
2. Read or write (perform operation)
3. Close the file
File Types?
In Python, there are two types of files. They are:
❑ Text files
❑ Binary files
Text files store the data in the form of characters. For example, if
we store employee name “Jerald”, it will be stored as 6
characters and the employee salary 8900.75 is stored as 7
characters.
Text files are used to store characters or strings .
File Types?
Binary files store entire data in the form of bytes, i.e., a group of
8 bits each. For example, a character is stored as a byte and an
integer is stored in the form of 8 bytes (on a 64-bit machine).
When the data is retrieved from the binary file, the programmer
can retrieve the data as bytes.
Binary files can be used to store text, images, audio and video.
Image files are generally available in .jpg, .gif or .png formats.
We cannot use text files to store images as the images do not
contain characters.
What Is File Handling?
Computer programs can import data from and export
data to files outside the code.
Read - Get data
Your code External file
from a file into your
program
Write/Append - send
data from your program
into a file
File Permissions
Read - File can be ‘looked at’ by the program
r but not changed. Error if the file doesn’t
already exist.
Append - File can be added to. File is created if
a
it doesn’t already exist.
Write - Overwrites existing data, starting from
w the beginning of the file. File is created if it
doesn’t already exist.
Read From a File
Read From A File - The Algorithm
1. Connect to and open the file
a. Give the file name and path
b. Set the permissions for opening
2. Read the contents into a variable
3. Output the variable
4. Close the file.
4. ‘r’ means read
Read All From A File - How To Code only. The program
can look at data from
1. Create a new variable 2. ‘open’ tells the the file but not change
to store the contents of program to open the it.
the file. file.
myFile = open("test.txt", "r")
for line in myFile:
3. Put the
print(line)
<path>+whole
myFile.close() filename
Read From A File - How To Code
5. ‘for’ is another type of 6. ‘line in myFile’ sets the
loop. It has a fixed length length of the loop to the
so does not need a number of lines in the
condition. external file.
myFile = open("test.txt", "r")
for line in myFile: 7. Outputs each line from
print(line) the file one by one. The
loop moves through each
myFile.close() one.
8. ALWAYS close the file once you have finished
with it.
Read Functions
read(n)
– Read at most n characters form the file. Reads till end of file if it is negative or None.
For example:
f = open(“text.txt”)
print (f.read()) # Reads the entire file
f.close()
f = open(“text.txt”)
print(f.read(5)) # Reads the first 5 characters of the file
f.close()
• readline(n=-1)
– Read and return one line from the file. Reads in at most n bytes if specified.
For example:
f = open(“text.txt)
print(f.readline())#Reads the first line of the file
f.close()
Read Functions
• readlines(n=-1)
– Read and return a list of lines from the file. Reads in at most n
bytes/characters if specified.
For example:
f = open(“text.txt”)
data = f.readlines()
for line in data:
print(line)
Write & Append to a File
4. ‘w’ means write. If
Write To A File - How To Code there’s an existing file
1. Create a new variable 2. ‘open’ tells the with this name Python
to store the contents of program to open the will open it. If not it
the file. file. will create it.
myFile = open("test.txt", "w")
myFile.write(“Andy”)
3. Put the whole
filename
myFile.close()
5. Put the data or variable
to be written
Append To A File - How To Code
4. ‘a’ means append.
1. Create a new variable 2. ‘open’ tells the This means ‘add to
to store the contents of program to open the the end’ of the file.
the file. file.
myFile = open("test.txt", "a")
myFile.write(“Andy”)
3. Put the whole
filename
myFile.close()
5. Put the data or variable
to be written