2
3 Lesson objectives
3 File handling
3 Opening and reading files
3 Source Code
PYTHON PROGRAMMING
3
By the end of this lesson, you should be able to:
Understand the importance of file handling
Learn how to open and read external files
File handling in Python refers to the ability to work with files, which are external resources used to store data
persistently. Python provides built-in functions and modules that allow programmers to perform various operations
on files, such as creating, reading, writing, and deleting files.
Open the file: You need to use the built-in open() function to open the file in the desired mode for reading. The open()
function takes two arguments: the file name (including the path if the file is in a different directory) and the mode
in which you want to open the file. For reading, use the mode ‘r’. For example:
import csv
file = open("[Link]", "r")
contents = [Link]()
print(contents)
[Link]()
with open('employee_data.csv','r') as csv_file:
csv_reader = [Link](csv_file)
line_count=0
for row in csv_reader:
if line_count ==0:
line_count+=1
print(f'{row["name"]} works in the {row["department"]} department. The
employee\'s ID is {row["employee_id"]}.')
line_count+=1
PYTHON PROGRAMMING