Python File Manipulation
Student Notes
1. Introduction to File Manipulation
A file is a collection of data stored permanently on a storage device such as a hard disk or
SSD. When a Python program ends, the data stored in variables is lost because it is
stored only in memory (RAM).
To store data permanently, we use files. Python provides built-in functions that allow us to
create, read, write and modify files easily.
Definition
File Manipulation is the process of creating, opening, reading, writing, updating and
closing files using a programming language.
2. Why Do We Need File Handling?
Suppose a school stores student names inside a Python program.
name = "Rahul"
If the program is closed, this data disappears. To keep the information permanently, it
should be stored inside a file.
Real Life Examples
Student Management System
Bank Account Details
Hospital Records
Employee Database
Library Management System
Without file handling, every time the program starts, we would have to enter all the
data again.
3. Types of Files
Python mainly works with two types of files.
Type Description
Text File Stores data in readable text format (.txt, .csv etc.)
Binary File Stores data in binary format (images, audio, objects etc.)
Difference Between Text File and Binary File
Text File Binary File
Human readable Not human readable
Stores characters Stores bytes
.txt, .csv .dat, .bin, .pickle
4. File Handling Process
Every file operation follows four basic steps.
Open File
│
▼
Read / Write Data
│
▼
Process the Data
│
▼
Close File
Always close the file after completing the operation to avoid data loss.
5. Opening and Closing Files
Python uses the open() function to open a file.
Syntax
file_object = open("filename","mode")
Example
file = open("[Link]","r")
Where
[Link] → File Name
r → Mode
Closing a File
After completing all operations, the file should be closed using the close() function.
[Link]()
Closing a file releases the system resources and saves any pending changes.
6. File Modes
A file mode tells Python how the file should be opened.
Mode Description
r Read existing file.
w Write data. Creates a new file or overwrites existing data.
a Append data at the end of the file.
x Create a new file. Generates an error if the file already exists.
rb Read binary file.
wb Write binary file.
Remember
r → Read only
w → Write (Old data is removed)
a → Add new data without deleting old data
x → Create new file
7. Reading Text Files
Python provides different methods to read the contents of a text file.
1. read()
Reads the complete file.
file = open("[Link]","r")
print([Link]())
[Link]()
Example Output
Rahul
Anu
Akash
2. readline()
Reads only one line at a time.
file = open("[Link]","r")
print([Link]())
[Link]()
Output
Rahul
3. readlines()
Reads all lines and stores them inside a list.
file = open("[Link]","r")
print([Link]())
[Link]()
Output
['Rahul\n','Anu\n','Akash\n']
Use read() for the entire file, readline() for a single line and readlines() when you
need a list of all lines.
8. Writing Text Files
Writing means storing data inside a file. Python mainly uses the w mode for writing.
Syntax
file = open("[Link]","w")
[Link]("Welcome to Python")
[Link]()
Output
[Link]
-------------------------
Welcome to Python
-------------------------
Explanation
The file is opened in write mode.
If the file does not exist, Python creates it.
If the file already exists, its old contents are removed.
The new text is written into the file.
The file is closed using close().
Important Points
The w mode deletes the existing contents of the file.
Always close the file after writing.
Use write() to store text into a file.
9. Appending Data to a Text File
Sometimes we need to add new information to an existing file without deleting the old
data. In such cases, Python uses the append mode (a).
Append Mode (a)
Append mode adds new data at the end of the file. The existing contents of the file are
not removed.
Syntax
file = open("[Link]","a")
[Link]("Akash\n")
[Link]()
Example
Before Appending
Rahul
Anu
Python Program
file = open("[Link]","a")
[Link]("Akash\n")
[Link]()
print("Data Added Successfully")
Output
Data Added Successfully
After Appending
Rahul
Anu
Akash
Explanation
The file is opened in append mode.
The write() function adds data at the end.
Old data remains unchanged.
The file is closed after writing.
Difference between w and a
w a
Deletes old data. Keeps old data.
Starts writing from the beginning. Writes at the end.
10. Writing and Reading Data Files
A data file is a file used to store information such as names, marks, employee details or
any other data generated by a program. Although data files are often simple text files, they
are used to store structured information.
Writing Data into a File
file = open("[Link]","w")
[Link]("Rahul 85\n")
[Link]("Anu 92\n")
[Link]("Akash 76\n")
[Link]()
Contents of [Link]
Rahul 85
Anu 92
Akash 76
Reading Data from a File
file = open("[Link]","r")
data = [Link]()
print(data)
[Link]()
Output
Rahul 85
Anu 92
Akash 76
Explanation
Open the file in read mode.
Use read() to read all data.
Display the contents.
Close the file.
11. Binary Files
A Binary File stores data in the form of bytes instead of characters. These files cannot be
read directly by humans.
Examples of Binary Files
Images (.jpg, .png)
Videos (.mp4)
Audio Files (.mp3)
PDF Files
Python Pickle Files
Text File Binary File
Stores characters Stores bytes
Human readable Machine readable
Uses r and w modes Uses rb and wb modes
Binary files are mainly used to store images, videos, objects and other non-text data.
12. Pickle Module
Python provides a built-in module called pickle to store Python objects inside binary files.
Using the pickle module, we can save an entire object into a file and retrieve it later.
Why Pickle?
Stores complete Python objects.
Easy to save and retrieve data.
Useful for large applications.
Supports binary files.
Flow Diagram
Python Object
[Link]()
Binary File
[Link]()
Python Object
13. Writing Objects into a Binary File ([Link])
Syntax
[Link](object,file)
Example
import pickle
student = {
"Name":"Rahul",
"Age":20,
"Mark":90
file = open("[Link]","wb")
[Link](student,file)
[Link]()
print("Object Stored Successfully")
Output
Object Stored Successfully
Explanation
Import the pickle module.
Create a Python object.
Open a binary file using wb mode.
Store the object using [Link]().
Close the file.
14. Reading Objects from a Binary File ([Link])
Syntax
object = [Link](file)
Example
import pickle
file = open("[Link]","rb")
data = [Link](file)
print(data)
[Link]()
Output
{'Name':'Rahul','Age':20,'Mark':90}
Explanation
Open the binary file in rb mode.
Use [Link]() to retrieve the object.
The original Python object is restored.
Close the file.
Remember
dump() → Writes an object to a binary file.
load() → Reads an object from a binary file.
Always use wb for writing and rb for reading binary files.
15. Directory Manipulation
A directory (also called a folder) is a location on a storage device where files and other
folders are stored. Python provides the os module to perform directory and file operations
such as creating folders, deleting folders, renaming files and changing the current working
directory.
Definition
Directory Manipulation is the process of creating, deleting, renaming and managing
folders and files using Python.
16. The os Module
The os module is a built-in Python module used to interact with the operating system.
Before using directory functions, the module must be imported.
Syntax
import os
Most directory operations are performed using the os module.
17. Common Directory Functions
Function Purpose
[Link]() Returns the current working directory.
[Link]() Changes the current working directory.
[Link]() Creates a new directory.
[Link]() Removes an empty directory.
[Link]() Renames a file or directory.
[Link]() Deletes a file.
[Link]() Displays all files and folders in a directory.
18. Getting the Current Working Directory
The getcwd() function returns the current working directory.
Program
import os
print([Link]())
Sample Output
C:\Users\Student\Documents
Explanation
Import the os module.
Call getcwd().
Python displays the current folder path.
19. Creating a Directory
The mkdir() function creates a new folder.
Syntax
[Link]("FolderName")
Example
import os
[Link]("PythonNotes")
print("Folder Created")
Output
Folder Created
20. Removing a Directory
The rmdir() function removes an empty folder.
Program
import os
[Link]("PythonNotes")
print("Folder Deleted")
Output
Folder Deleted
Note: The folder must be empty before using rmdir(). Otherwise Python generates an
error.
21. Renaming a File or Directory
The rename() function changes the name of a file or directory.
Syntax
[Link]("[Link]","[Link]")
Example
import os
[Link]("[Link]","[Link]")
print("File Renamed")
Output
File Renamed
22. Deleting a File
The remove() function deletes a file permanently.
Syntax
[Link]("[Link]")
Example
import os
[Link]("[Link]")
print("File Deleted")
Output
File Deleted
Once a file is deleted using [Link](), it cannot be recovered easily. Always
ensure that the correct file is selected before deleting it.
23. Listing Files and Folders
The listdir() function displays all files and folders available in a directory.
Program
import os
print([Link]())
Sample Output
['[Link]',
'[Link]',
'PythonNotes',
'[Link]']
Explanation
Imports the os module.
Reads the contents of the current directory.
Displays all files and folders as a list.
24. Changing the Current Directory
The chdir() function changes the current working directory.
Syntax
[Link]("FolderName")
Example
import os
[Link]("PythonNotes")
print([Link]())
Output
C:\Users\Student\Documents\PythonNotes