Manipulating Files, Directories, and Text Files in Python
Presented by:
Dinesh Budha (10), Pralhad Kalakheti (21), Niranjan Kumar Singh (22)
2nd Semester, BME/2025
Introduction to File Handling
- Allows programs to create, read, write, delete files.
- Python has built-in support for these operations.
Creating a File
file = open("example.txt", "w")
file.write("Hello, this is a new file!")
file.close()
Output:
Hello, this is a new file!
Writing to a File
file = open("example.txt", "w")
file.write("Overwriting previous content.")
file.close()
Output:
Overwriting previous content.
Reading from a File
file = open("example.txt", "r")
content = file.read()
print(content)
file.close()
Output:
Overwriting previous content.
Summary for Student 1
- Operations: Create, Write, Read
- Used open() with modes: w, r
Appending to a File
file = open("example.txt", "a")
file.write("\nAppended line.")
file.close()
Output:
Overwriting previous content.
Appended line.
Deleting a File
import os
os.remove("example.txt")
Output:
File removed.
Creating a Directory
import os
os.mkdir("new_folder")
Output:
Folder new_folder created.
Removing a Directory
import os
os.rmdir("new_folder")
Output:
Folder removed.
Summary for Student 2
- Operations: Append, Delete File, Create/Remove Directory
- Directory must be empty to remove.
File Read Modes
"r" : Read (default)
"w" : Write (overwrite)
"a" : Append
"r+" : Read & Write
Reading Line by Line
file = open("lines.txt", "r")
for line in file:
print(line.strip())
file.close()
Output:
First line
Second line
Third line
Directory Structure Example
import os
print(os.getcwd())
print(os.listdir("."))
Output:
/user/home/project
[file1.txt, example.txt, folder]
Limitations of Presentation
- Only basic operations covered.
- Binary files and error handling not included.
Final Conclusion
- Simple but powerful tools.
- Essential for effective Python applications.