File Handling
Two types of files
1. Text files: human readable data
• Extensions like .txt, .csv, .json, .xml, etc.
2. Binary files: cannot be interpreted by humans directly.
• Multi-media files
• MP4, Mp3, jpeg, png, etc.
Operations on a file
Open —> Read/Write —> Close
Open a file
open(file_name, mode)
file = open('[Link]', 'r')
print(file)
<_io.TextIOWrapper name='[Link]' mode='r' encoding='UTF-8'>
Opening a file by default in read mode
file = open('[Link]')
print(file)
<_io.TextIOWrapper name='[Link]' mode='r' encoding='UTF-8'>
Modes of opening a file
Mode Description
'r' read mode
it will open the file in read mode
if the file is not present, it will raise an error. FileNoteFoundError
By default a file opens in read mode.
Cursor will be at the beginning of the file.
'w' write mode
if the file is not present, then it will create a new file and write the content into
it.
if the file is present, then it will overwrite the data in the existing [Link] xv
'a' Opens the file in append mode
if the file is present, it will add the data at the end of the file.
but if the file is NOT present, it will create a new file and add the data into
it.
r+ Read and write the data
File must be present, if it is not present it will raise an error.
FileNotFoundError.
Cursor will be at the beginning of the file.
w+ write and read mode
if the file is not present, it will create a new file and data will be added.
if the file is present, the existing data will be truncated.
cursor will be at the beginning of the file.
a+ append and read mode
same as w+ mode
it will add the new data at the end of the existing file.
rb same as all the above modes but for binary files.
wb
ab
rb+
wb+
ab+
Reading Operation
1. read() : will read all the content of the file character by character.
file = open('[Link]')
data = [Link]()
print(data)
Output: all the contents of [Link]
beige
green
scarlet
silver
bronze
slate
yellow
orange
jade
lavender
magnolia
magenta
turquoise
black
grey
russet
maroon
mango
mint
purple
red
pink
white
cream
navy
olive
brown
violet
cyan
amber
aqua
azure
copper
fawn
fuschia
gold
indigo
ivory
mauve
mulberry
peach
periwinkle
plum
rose
sage
2. read(SIZE): we can pass the number of characters to be read from the file using the
SIZE parameter. This will read only a specified number of characters from the file.
file = open('[Link]')
data = [Link](14)
print(data)
beige
green
sc
3. readline(): read the data from the file line by line but will be able to read only one line at
a time, starting from the first line.
file = open('[Link]')
data = [Link]()
print(data)
beige
4. readlines(): this will read all the lines from the file one by one and returns a list of string
containing the lines from the file.
5. file = open('[Link]')
6. data = [Link]()
7. print(data)
['beige\n', 'green\n', 'scarlet\n', 'silver\n', 'bronze\n', 'slate\n', 'yellow\n', 'orange\n', 'jade\n',
'lavender\n', 'magnolia\n', 'magenta\n', 'turquoise\n', 'black\n', 'grey\n', 'russet\n',
'maroon\n', 'mango\n', 'mint\n', 'purple\n', 'red\n', 'pink\n', 'white\n', 'cream\n', 'navy\n',
'olive\n', 'brown\n', 'violet\n', 'cyan\n', 'amber\n', 'aqua\n', 'azure\n', 'copper\n', 'fawn\n',
'fuschia\n', 'gold\n', 'indigo\n', 'ivory\n', 'mauve\n', 'mulberry\n', 'peach\n', 'periwinkle\n',
'plum\n', 'rose\n', 'sage']
Close a file
• This will close the instance of the file.
• We will have to reopen the file in case we have to perform any action.
file = open('[Link]')
data = [Link]()
print(data)
[Link]()
Homework: 19/05/2025
1. Write a program to open a file in each of the above modes one by one and close the file
each time.
2. Write a Python program to open [Link], read all lines, and print them one by one.
3. Write a program to count the total number of color names in the file.
4. Open the file and display only the first five color names.
5. Ask the user to input a color and check if it exists in the file.
# Open the file and display only the first five color names.
file = open('[Link]', 'r')
data = [Link]()
# Method 1: Using for loop
print("Result using Loops")
for i in range(5):
print(data[i])
# Method 2: Using slicing
print("Result using Sllcing: ")
print(data[0:5:1])
# Ask the user to input a color and check if it exists in the file.
file = open('[Link]', 'r')
lines = [Link]()
print("Original: ", lines)
# removing '\n' from the end of each line
for i in range(len(lines)):
lines[i] = lines[i].strip()
print("After cleaning: ", lines)
color = input("Enter a color name to check: ")
if color in lines:
print("Color exists.")
else:
print("Color does not exist.")
String Methods [Link]
List Methods [Link]
# Display all color names from the file that start with the letter ‘m’
# Ask the user to input a color and check if it exists in the file.
file = open('[Link]', 'r')
lines = [Link]()
# removing '\n' from the end of each line
for i in range(len(lines)):
lines[i] = lines[i].strip()
print("After cleaning: ", lines)
# iterate over each line and check if any of them starts with 'm'
for i in range(len(lines)):
if lines[i].startswith('m'):
print(lines[i])
# Read the file and print only those colors whose names are longer
than 5 characters.
Writing Operation
• Writing content into the file.
1. write(string): accepts a string as an argument and writes the content into the file.
2. writelines(list of string): accepts a list of string as an argument and can write multiple
lines into a file
Writing content into the file using write ()
file = open('data_new.txt', 'w')
content = "prisha is learning file handling."
[Link](content)
writelines()
file = open('data_new.txt', 'w')
content = ["molly is learning file handling.\n",
'arya is learning file handling.\n',
'harry is teaching file handling.\n'
]
[Link](content)
Append Operation
• Adds the content at the end of the file.
• All the functions will be same as write file functions, but the file must open in append
mode ‘a’
file = open('data_new.txt', 'a')
content = ["prisha is learning file handling.\n",
‘arya is learning file handling.\n',
'molly is teaching file handling.\n'
]
[Link](content)