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
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) writesExample
Reading line by line: with open("notes.txt") as f: for line in f: print(line.strip()) prints each line without extra blank lines. The with statement closes the file automatically, even if an error occurs.
Exam tip
read() reads everything, readline() one line, readlines() a list of lines.
Topic 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.
Example
Choosing a mode: "w" erases notes.txt and starts fresh; "a" adds to the end; "r+" reads and writes without erasing; "rb" reads an image as bytes. Specifying encoding="utf-8" avoids errors with Hindi or Punjabi text.
Exam tip
Opening an existing file in "w" mode deletes its contents — a common mistake.
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).
Example
Moving the file pointer: after writing "Synetic Business School", f.tell() returns 23 (position at the end). f.seek(0) moves back to the start so f.read(7) returns "Synetic". os.rename("a.txt", "b.txt") renames a file and os.remove("b.txt") deletes it.
Exam tip
Use os and os.path (or pathlib) for directory operations.
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)Example
Class and instance attributes: with class Student: college = "SBS" and an __init__ setting self.name, s1 = Student("Asha") and s2 = Student("Ravi") share college = "SBS" but each has its own name.
Exam tip
__init__ is the constructor; self refers to the current object.
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.
Example
Attribute functions: getattr(s1, "marks", 0) returns 88 (or 0 if missing); hasattr(s1, "grade") returns False; setattr(s1, "grade", "A") adds it; delattr(s1, "grade") removes it.
Exam tip
getattr, setattr, hasattr and delattr work with attribute names as strings.
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}Example
Inspecting a class: Student.__name__ gives 'Student', Student.__module__ gives '__main__', s1.__dict__ shows {'name': 'Asha', 'marks': 88}, and Student.__doc__ shows the class docstring.
Exam tip
Learn __dict__, __doc__, __name__, __module__ and __bases__.
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.
Example
Reference counting: a = [1, 2]; b = a gives the list two references. After del a and b = None, its count drops to zero and Python frees it. Objects that refer to each other in a cycle are freed by the cyclic garbage collector (the gc module).
Exam tip
Python uses reference counting plus a cyclic garbage collector — no manual free() is needed.
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.
