Unit 4: File management and OOP
Fundamentals of Computer and Programming in Python notes · PTU syllabus (PGCA1902)
On this page
Unit summary
Programs must store data in files and model real-world things as objects. This unit covers file operations — opening, modes, attributes, encoding and closing — read, write, tell and seek, renaming and deleting files, directories, and object-oriented programming in Python — designing classes, creating objects, accessing and editing attributes, built-in class attributes and garbage collection.
After this unit you can
- Open, read, write and close files in different modes
- Use tell, seek, rename, delete and directory functions
- Design classes and create objects
- Use built-in class attributes and explain garbage collection
PTU syllabus topics
- File operations (opening, modes, attributes, encoding, closing)
- read/write/tell/seek methods
- renaming and deleting files
- directories
- OOP concepts in Python — designing classes
- creating objects
- accessing and editing attributes
- built-in class attributes
- garbage collection
'r'
Read (default)
Reads from the start
'w'
Write
Overwrites it
'a'
Append
Adds to the end
'r+'
Read and write
Keeps contents
'b' suffix
Binary mode, e.g. 'rb'
Reads bytes
Topic 1
Opening, reading, writing and closing files
pythonwith open("notes.txt", "w") as f: # with closes the file automatically
f.write("Line 1\n")
with open("notes.txt", "r") as f:
for line in f:
print(line.strip())| Mode | Meaning |
|---|---|
| "r" | Read (default) |
| "w" | Write (overwrites) |
| "a" | Append |
| "rb" / "wb" | Read / write binary |
Pickle saves Python objects to binary files: pickle.dump(obj, f) and obj = pickle.load(f).
pythonimport csv, json
with open("data.csv", newline="") as f:
for row in csv.reader(f): print(row)
with open("data.json") as f:
data = json.load(f) # json.dump(obj, f) writesTopic 2
File modes, attributes and encoding
- r
- Read (default); error if missing
- w
- Write; creates or truncates
- a
- Append; creates if missing
- x
- Exclusive create; error if it exists
- b and t
- Binary or text (default) — rb, wb
- +
- Read and write — r+, w+, a+
- File object attributes: f.name, f.mode, f.closed, f.encoding. Encoding: open("a.txt", encoding="utf-8") avoids errors with non-English text.
Topic 3
tell, seek, renaming, deleting and directories
pythonwith open("notes.txt", "w+", encoding="utf-8") as f:
f.write("Synetic Business School\n")
print(f.tell()) # current position in bytes
f.seek(0) # move to the start
print(f.read(7)) # Synetic
import os
os.rename("notes.txt", "sbs.txt")
os.remove("sbs.txt") # delete a file
os.mkdir("reports") # make a directory
print(os.getcwd(), os.listdir(".")) # current directory and contents
os.chdir("reports"); os.chdir("..")
os.rmdir("reports") # remove an empty directory- pathlib offers an object-oriented alternative: Path("reports").mkdir(exist_ok=True).
Topic 4
Designing classes and creating objects
pythonclass Student:
college = "SBS" # class attribute shared by all objects
def __init__(self, name, marks): # constructor
self.name = name # instance attributes
self.marks = marks
def grade(self): # method
return "A" if self.marks >= 75 else "B"
def __str__(self):
return f"{self.name} ({self.marks})"
s1 = Student("Aman", 82) # creating objects
s2 = Student("Riya", 68)
print(s1, s1.grade(), Student.college)Topic 5
Accessing and editing attributes
pythons1.marks = 88 # edit directly
setattr(s2, "marks", 72) # edit with a function
print(getattr(s1, "name"), hasattr(s1, "age"))
s1.age = 20 # add a new attribute to one object
delattr(s1, "age") # delete it- Encapsulation by convention: a single underscore (_fee) marks internal use; a double underscore (__fee) triggers name mangling. Inheritance: class PGStudent(Student) reuses and extends Student.
Topic 6
Built-in class attributes
- __dict__
- Dictionary of the class's (or object's) attributes
- __doc__
- Documentation string
- __name__
- Class name
- __module__
- Module in which the class is defined
- __bases__
- Tuple of base classes
pythonprint(Student.__name__, Student.__module__, Student.__bases__)
print(s1.__dict__) # {'name': 'Aman', 'marks': 88}Topic 7
Garbage collection
- Python frees memory automatically. Reference counting: each object counts the references to it; when the count drops to zero, the memory is reclaimed. A cyclic garbage collector (gc module) finds groups of objects that refer only to each other.
pythonimport sys, gc
a = [1, 2, 3]
print(sys.getrefcount(a)) # references (one extra for the call)
b = a; del a # object still alive through b
del b # count reaches zero → freed
gc.collect() # force a cycle collection- A destructor __del__(self) runs just before an object is destroyed.
Key terms
- File mode
- Letter code deciding how a file is opened
- seek()
- Moves the file pointer to a position
- Class
- Blueprint defining attributes and methods
- self
- Reference to the current object in a method
- Garbage collection
- Automatic reclamation of unused memory
Quick revision
- open, modes, with, read, readline, readlines, write, close; encoding.
- tell, seek; os.rename, os.remove, mkdir, listdir, rmdir.
- class, __init__, self, class vs instance attributes, methods, __str__.
- getattr, setattr, hasattr, delattr; _ and __ conventions.
- __dict__, __doc__, __name__, __module__, __bases__; reference counting, gc, __del__.
Important exam questions
Practice questions written to the PTU exam pattern for this unit's syllabus: short answers (Section A style) and long answers (Sections B and C style).
Short-answer questions
- Q1.Distinguish modes w and a.
- Q2.What does tell() return?
- Q3.How is a file deleted in Python?
- Q4.What is self?
- Q5.Distinguish class and instance attributes.
- Q6.How does Python collect garbage?
Long-answer questions
- Q1.Explain file handling in Python with programs.
- Q2.Explain directory operations with the os module.
- Q3.Explain classes and objects with a program.
- Q4.Explain built-in class attributes and garbage collection.
Stuck on this unit?
Message SBS on WhatsApp for help with Fundamentals of Computer and Programming in Python, or to ask about studying M.Sc IT at Synetic.
