csaccept.com is a computer awareness website dedicated to providing reliable and easy-to-understand information about computer technology and digital safety. The website focuses on educating students, beginners, and general users about computer basics, cyber security, emerging technologies, and practical IT skills. Through informative articles, quizzes, and real-life examples, csaccept.com aims to increase digital literacy and help users stay safe and confident in today’s technology-driven world.
Facebook ………………..
Instagram ……………..
Twitter ( X ) ……………..
YouTube
Full details of Working with Files and Directories in Python with suitable Examples
File handling is one of the most important concepts in programming. In real-world applications, programs often need to store data permanently, read previously stored information, or modify files. (csaccept.com)
Python provides simple and powerful tools for working with files and directories. With Python, we can create files, read data from files, write new data, manage directories, and even work with structured data formats like CSV and JSON.
This guide explains everything about Python File Handling and Directory Management with practical examples.
1. Introduction to File Handling in Python
A file is a named location on a storage device (such as a hard disk) used to store data permanently.
Unlike variables, which store data temporarily in memory, files allow data to remain available even after the program stops running.
Why File Handling is Important
File handling is used when programs need to:
- Store user data permanently
- Save logs or reports
- Read configuration settings
- Work with datasets
- Exchange data between programs
Python makes file handling simpler compared to many other programming languages.
2. Types of Files in Python
Python generally handles two types of files:
1. Text Files
Text files store data in human-readable format.
Examples:
file.txt
notes.txt
data.csv
Each line ends with a special character called a newline character (\n).
2. Binary Files
Binary files store data in binary format (0 and 1).
Examples:
image.jpg
video.mp4
program.exe
Binary files are not human readable.
3. Basic File Operation Steps
Every file operation in Python follows three basic steps:
Step 1 – Open the file
The file must be opened before performing any operation.
Step 2 – Perform operation
Operations may include:
- Reading
- Writing
- Appending
Step 3 – Close the file
After finishing work with the file, it should be closed.
4. Opening a File in Python
Python provides the open() function to open a file.
Syntax
file_object = open(file_name, access_mode)
Example:
fileptr = open("file.txt", "r")
if fileptr:
print("File opened successfully")
Output
File opened successfully
The open() function returns a file object, which allows us to perform operations like reading and writing.
5. File Access Modes in Python
Different modes determine how a file will be opened.
| Mode | Description |
|---|---|
| r | Read only mode |
| rb | Read binary mode |
| r+ | Read and write |
| w | Write mode (overwrite file) |
| wb | Write binary |
| w+ | Write and read |
| a | Append mode |
| ab | Append binary |
| a+ | Append and read |
6. Closing a File
After completing operations on a file, it is important to close it using close().
Syntax
file_object.close()
Example
fileptr = open("file.txt", "r")
print("File opened successfully")
fileptr.close()
Closing the file ensures that:
- Memory resources are released
- Data is saved properly
7. Writing Data to a File
To write data to a file, we open it using write mode (w) or append mode (a).
Example: Writing Data
fileptr = open("file2.txt", "w")
fileptr.write("Python is a powerful programming language.")
fileptr.close()
Output
A file named file2.txt will be created containing:
Python is a powerful programming language.
8. Appending Data to a File
Append mode allows adding new content without deleting existing data.
Example:
fileptr = open("file2.txt", "a")
fileptr.write("\nIt is widely used for data science and AI.")
fileptr.close()
9. Reading a File in Python
Python allows reading files using loops.
Example:
fileptr = open("file2.txt", "r")
for line in fileptr:
print(line)
fileptr.close()
Output
Python is a powerful programming language.
It is widely used for data science and AI.
Each iteration reads one line from the file.
10. Python OS Module for File Management
Python provides the os module to interact with the operating system.
This module allows us to:
- Rename files
- Delete files
- Create directories
- Remove directories
- Change directories
11. Renaming a File
Python provides os.rename() to rename files.
Example
import os
os.rename("file2.txt", "file3.txt")
The file file2.txt will be renamed to file3.txt.
12. Deleting a File
We can delete files using os.remove().
Example
import os
os.remove("file3.txt")
This will permanently delete the file.
13. Creating a Directory
Directories (folders) help organize files.
Python uses mkdir() to create a new directory.
Example
import os
os.mkdir("newfolder")
A new folder named newfolder will be created.
14. Get Current Working Directory
The getcwd() function returns the current working directory.
Example
import os
print(os.getcwd())
Output
C:\Users\Student\Documents
15. Changing Current Directory
Python uses chdir() to change the current directory.
Example
import os
os.chdir("newfolder")
Now the program will operate inside the newfolder directory.
16. Deleting a Directory
The rmdir() function deletes a directory.
Example
import os
os.rmdir("newfolder")
Note: The directory must be empty before deletion.
17. Working with CSV Files in Python
CSV stands for Comma Separated Values.
It is a simple text format used to store tabular data.
Example CSV file:
Name,Age,City
Rahul,22,Delhi
Priya,21,Mumbai
Amit,23,Kanpur
Python provides the csv module to read and write CSV files.
18. Reading a CSV File
Example
import csv
with open("students.csv", "r") as file:
reader = csv.reader(file)
for row in reader:
print(row)
Output
['Name', 'Age', 'City']
['Rahul', '22', 'Delhi']
['Priya', '21', 'Mumbai']
19. Writing to a CSV File
Example
import csv
with open("students.csv", "w", newline="") as file:
writer = csv.writer(file)
writer.writerow(["Name", "Age", "City"])
writer.writerow(["Rahul", 22, "Delhi"])
writer.writerow(["Priya", 21, "Mumbai"])
20. CSV Writer Methods
| Function | Description |
|---|---|
| writerow() | Writes one row |
| writerows() | Writes multiple rows |
Example
data = [
["Amit", 23, "Kanpur"],
["Neha", 24, "Lucknow"]
]
writer.writerows(data)
21. Working with JSON Files
JSON stands for JavaScript Object Notation.
It is widely used for data exchange between applications and APIs.
Example JSON data
{
"name": "Rahul",
"age": 22,
"city": "Delhi"
}
Python provides the json module to work with JSON data.
Writing JSON File Example
import json
data = {
"name": "Rahul",
"age": 22,
"city": "Delhi"
}
with open("data.json", "w") as file:
json.dump(data, file)
Reading JSON File Example
import json
with open("data.json", "r") as file:
data = json.load(file)
print(data)
Output
{'name': 'Rahul', 'age': 22, 'city': 'Delhi'}
Conclusion
File handling is a fundamental concept in Python programming. It allows developers to store, retrieve, and manage data efficiently.
In this guide, we learned:
- File handling basics
- Opening and closing files
- Reading and writing files
- File access modes
- Python OS module for directory management
- Working with CSV files
- Working with JSON files
Understanding file operations is essential for building real-world applications such as databases, web apps, data analysis systems, and automation tools.
Students learning Python at CS Accept should practice these concepts with multiple examples to master file handling.
Short Question–Answers (Python File Handling)
1. What is file handling in Python?
File handling is the process of creating, reading, writing, and managing files using Python programs.
2. What is a file?
A file is a named location on disk used to store data permanently.
3. Why is file handling important?
It allows programs to store data permanently even after the program ends.
4. What function is used to open a file in Python?
The open() function is used.
5. What does the open() function return?
It returns a file object.
6. What are the main steps in file handling?
- Open file
- Perform operations (read/write)
- Close file
7. What are the two types of files in Python?
- Text files
- Binary files
8. What is text file mode?
It reads or writes files as readable characters.
9. What is binary mode?
Binary mode reads or writes data in binary format.
10. What does “r” mode mean?
It opens the file in read-only mode.
11. What does “w” mode mean?
It opens the file in write mode and overwrites existing data.
12. What does “a” mode mean?
It opens the file in append mode to add new data.
13. What does “r+” mode do?
It opens the file for both reading and writing.
14. What is the purpose of close() method?
It closes the file and releases system resources.
15. What happens if a file is not closed?
It may cause memory leaks or data loss.
16. Which module is used for OS operations in Python?
The os module.
17. What does os.rename() do?
It renames a file.
18. What does os.remove() do?
It deletes a file.
19. What does os.mkdir() do?
It creates a new directory.
20. What does os.getcwd() return?
It returns the current working directory.
21. What does os.chdir() do?
It changes the current working directory.
22. What does os.rmdir() do?
It removes a directory.
23. What is a CSV file?
CSV is a Comma Separated Values file used for tabular data.
24. Which module is used to work with CSV files?
The csv module.
25. What does csv.reader() do?
It reads data from CSV files.
26. What does csv.writer() do?
It writes data to CSV files.
27. What is writerow()?
It writes a single row to a CSV file.
28. What is writerows()?
It writes multiple rows to a CSV file.
29. What is JSON?
JSON is a data format used to store and exchange structured data.
30. Which module is used for JSON files?
The json module.
MCQ Quiz (With Answers)
1. Which function is used to open a file?
A. file()
B. open()
C. read()
D. write()
✅ Answer: B
2. Which mode opens a file in read-only mode?
A. r
B. w
C. a
D. x
✅ Answer: A
3. Which mode overwrites a file?
A. a
B. r
C. w
D. rb
✅ Answer: C
4. Which mode adds data to the end of file?
A. r
B. w
C. a
D. rb
✅ Answer: C
5. Which module interacts with operating system?
A. sys
B. os
C. math
D. csv
✅ Answer: B
6. Which function deletes a file?
A. os.delete()
B. os.remove()
C. os.erase()
D. os.clear()
✅ Answer: B
7. Which function renames a file?
A. os.rename()
B. os.change()
C. os.modify()
D. os.replace()
✅ Answer: A
8. Which function creates a directory?
A. os.create()
B. os.make()
C. os.mkdir()
D. os.dir()
✅ Answer: C
9. Which function returns current directory?
A. os.getcwd()
B. os.current()
C. os.dir()
D. os.path()
✅ Answer: A
10. Which function changes directory?
A. os.switch()
B. os.chdir()
C. os.move()
D. os.dirchange()
✅ Answer: B
11. Which function deletes directory?
A. os.rmdir()
B. os.remove()
C. os.delete()
D. os.dirremove()
✅ Answer: A
12. CSV stands for:
A. Character Separated Value
B. Comma Separated Value
C. Computer Separated Value
D. Column Stored Value
✅ Answer: B
13. Which module handles CSV files?
A. csv
B. json
C. os
D. sys
✅ Answer: A
14. Which function reads CSV file?
A. csv.read()
B. csv.reader()
C. csv.open()
D. csv.load()
✅ Answer: B
15. Which function writes CSV file?
A. csv.write()
B. csv.writer()
C. csv.save()
D. csv.insert()
✅ Answer: B
Python Practice Programs
Program 1 – Write Data to File
file = open("student.txt","w")
file.write("Name: Rahul\n")
file.write("Course: Python Programming")
file.close()
Program 2 – Read File
file = open("student.txt","r")
for line in file:
print(line)
file.close()
Program 3 – Append Data
file = open("student.txt","a")
file.write("\nCity: Prayagraj")
file.close()
Program 4 – Rename File
import os
os.rename("student.txt","studentdata.txt")
Program 5 – Delete File
import os
os.remove("studentdata.txt")
Program 6 – Create Directory
import os
os.mkdir("pythonfiles")
Program 7 – CSV Write Example
import csv
file = open("students.csv","w",newline="")
writer = csv.writer(file)
writer.writerow(["Name","Age","City"])
writer.writerow(["Rahul",22,"Delhi"])
file.close()
Program 8 – JSON Write Example
import json
data = {
"name":"Rahul",
"course":"Python",
"city":"Delhi"
}
file = open("data.json","w")
json.dump(data,file)
file.close()
SEO Optimized Blog Version (For csaccept.com)
SEO Title
Python File Handling Tutorial – Working with Files, Directories, CSV & JSON
SEO Keywords
Python File Handling
Python File I/O
Python CSV File Tutorial
Python JSON Tutorial
Python Directory Management
Python File Handling Tutorial – Complete Guide for Beginners
Python file handling allows developers to store, read, and manage data permanently using files. It is one of the most important topics for beginners learning Python programming.
In this tutorial, we will learn:
- File operations in Python
- File access modes
- Writing and reading files
- OS module operations
- CSV file handling
- JSON file handling
What is File Handling?
File handling refers to the process of storing and retrieving data from files. Unlike variables, files store data permanently on disk.
Python provides built-in functions like open(), read(), write(), and close() to work with files.
Steps for File Handling
- Open the file
- Perform operation
- Close the file
Python File Modes
- r – Read file
- w – Write file
- a – Append file
- r+ – Read and write
Python OS Module
Python also provides the os module to interact with the operating system.
It helps to:
- rename files
- delete files
- create directories
- change directories
Working with CSV and JSON
Python supports working with structured data formats like:
- CSV files for tabular data
- JSON files for API and structured data exchange
These are widely used in data science, machine learning, and web applications.

