Computer Science
|| CHAPTER 2 FILE HANDLING IN PYTHON
CHAPTER 2: FILE HANDLING IN PYTHON
Introduction to Files
• In Python, data stored in variables is temporary and disappears after the program ends.
• To store data permanently, we use files, which are saved on secondary storage (e.g., hard disks).
• Files allow us to store inputs, outputs, and objects for later use.
• A Python file (source code) is saved with a .py extension.
File: A file is a collection of data or information stored on a computer or storage device.
Types of Files
Files can be classified into two major types:
Text Files
• Human-readable and stored using characters like letters, digits, symbols.
Examples: .txt, .py, .csv, etc.
• Stored using encoding formats like ASCII, Unicode.
• Each character is represented by its byte equivalent.
• End of Line (EOL) character (\n) is used to separate lines.
Example: The ASCII value of 'A' is 65 → Binary: 1000001
Binary Files
• Not human-readable (appear as symbols or garbage in text editors).
• Store data such as images, audio, video, compressed or executable files.
• Readable only with appropriate programs.
Opening a File
• Files are opened using the open() function which returns a file object.
Syntax: file_object = open("filename", "mode")
• Preferred method for file operations as it auto-closes the file.
Syntax: with open("myfile.txt", "r+") as myObject:
Closing a File
• Closes file after use to free system resources.
Syntax: file_object.close()
File Access Modes with Examples
Read Mode – r Example: f = open(“myfile.txt”,”r”)
Write Mode – w Example: f = open(“myfile.txt”,”w”)
Append Mode - a Example: f = open(“myfile.txt”,”a”)
File Access Modes
Mode Description File Pointer Position
r Read only Beginning
rb Read binary Beginning
r+ Read and write Beginning
w Write only (overwrites if exists) Beginning
wb+ Write and read binary (overwrites) Beginning
a Append (creates file if it doesn’t exist) End
a+ Append and read End
|| CHAPTER 2 FILE HANDLING IN PYTHON Computer Science
Writing to a Text File
Syntax: write()
file_object.write(string)
• Writes a single string to the file.
• Returns the number of characters written.
Example: write()
myobject = open("myfile.txt", 'w')
myobject.write("Hey I have started using files in Python\n")
myobject.close()
Writing numbers:
marks = 58
myobject.write(str(marks))
Syntax: writelines()
file_object.writelines(list_of_strings)
• Writes multiple strings to the file.
• Takes an iterable like a list or tuple.
Example: writelines()
• Writes a sequence (like a list or tuple) of strings.
lines = ["Hello everyone\n", "Writing multiline strings\n", "This is the third line"]
myobject.writelines(lines)
Reading from a Text File
Syntax: read(n)
file_object.read(n)
• Reads n bytes from the file.
Example: read(n)
• Reads n bytes from the file.
myobject = open("myfile.txt", 'r')
print(myobject.read(10))
myobject.close()
Syntax: read()
file_object.read()
• Reads the entire content of the file.
Example: read()
• Reads the entire file content.
myobject = open("myfile.txt", 'r')
print(myobject.read())
myobject.close()
Syntax: readline(n)
file_object.readline(n)
• Reads one line or up to n bytes until newline character.
|| CHAPTER 2 FILE HANDLING IN PYTHON Computer Science
Example: readline(n)
• Reads one line or n bytes until newline.
myobject = open("myfile.txt", 'r')
print(myobject.readline(10))
myobject.close()
Syntax: readlines()
file_object.readlines()
• Reads all lines and returns them as a list.
Example: readlines()
• Reads all lines and returns a list.
myobject = open("myfile.txt", 'r')
print(myobject.readlines())
myobject.close()
Splitting into words:
for line in lines:
words = line.split()
print(words)
Using splitlines():
for line in lines:
print(line.splitlines())
Complete Example from Text
fobject = open("testfile.txt", "w")
sentence = input("Enter the contents to be written in the file: ")
fobject.write(sentence)
fobject.close()
print("Now reading the contents of the file: ")
fobject = open("testfile.txt", "r")
for str in fobject:
print(str)
fobject.close()
File Offset Methods
Syntax: tell()
file_object.tell()
• Returns current position of file pointer.
• Returns current file pointer position.
file_object.tell()
Syntax: seek(offset, reference_point)
file_object.seek(offset, reference_point)
• Moves pointer to specified position from reference point (0 = start, 1 = current, 2 = end).
• Moves pointer to specified position.
file_object.seek(5, 0) # Move to 5th byte from start
|| CHAPTER 2 FILE HANDLING IN PYTHON Computer Science
Program Example:
fileobject = open("testfile.txt", "r+")
str = fileobject.read()
print(str)
print("Initially, position:", fileobject.tell())
fileobject.seek(0)
print("Now at beginning:", fileobject.tell())
fileobject.seek(10)
print("Pointer at:", fileobject.tell())
print(fileobject.read())
fileobject.close()
Creating and Traversing a Text File
Creating File and Writing Data
fileobject = open("practice.txt", "w+")
while True:
data = input("Enter data to save in the text file: ")
fileobject.write(data)
ans = input("Do you wish to enter more data?(y/n): ")
if ans == 'n': break
fileobject.close()
Displaying File Contents
fileobject = open("practice.txt", "r")
str = fileobject.readline()
while str:
print(str)
str = fileobject.readline()
fileobject.close()
Combined Read/Write Program
fileobject = open("report.txt", "w+")
while True:
line = input("Enter a sentence ")
fileobject.write(line + "\n")
choice = input("Do you wish to enter more data? (y/n): ")
if choice.lower() == 'n': break
print("File position:", fileobject.tell())
fileobject.seek(0)
print("Reading contents:")
print(fileobject.read())
fileobject.close()
|| CHAPTER 2 FILE HANDLING IN PYTHON Computer Science
Pickle Module
Pickling
• Process of converting Python objects to a byte stream (serialization).
• Can store complex objects like lists, dictionaries.
Unpickling
• Restores the byte stream back into original object (deserialization).
Import Statement
import pickle
Syntax for dump()
pickle.dump(object, file_object)
Example for dump()
listvalues = [1, "Geetika", 'F', 26] fileobject = open("mybinary.dat", "wb")
pickle.dump(listvalues, fileobject) fileobject.close()
Syntax for load()
variable = pickle.load(file_object)
Example for load()
fileobject = open("mybinary.dat", "rb")
objectvar = pickle.load(fileobject)
fileobject.close()
print(objectvar)
Complete Program Example
import pickle
bfile = open("empfile.dat", "ab")
recno = 1
while True:
eno = int(input("Employee number: "))
ename = input("Name: ")
ebasic = int(input("Basic Salary: "))
allow = int(input("Allowances: "))
totsal = ebasic + allow
edata = [eno, ename, ebasic, allow, totsal]
pickle.dump(edata, bfile)
if input("More records? (y/n): ").lower() == 'n': break
print("File size:", bfile.tell())
bfile.close()
print("Reading employee records")
try:
with open("empfile.dat", "rb") as bfile:
while True:
edata = pickle.load(bfile)
print(edata)
except EOFError:
pass