Unit 4 of 4 · M.Sc IT Sem 1

Unit 4: File management and OOP

Fundamentals of Computer and Programming in Python notes · PTU syllabus (PGCA1902)

3 min read7 topics10 exam questions
On this page
  1. Unit summary
  2. Opening, reading, writing and closing files
  3. File modes, attributes and encoding
  4. tell, seek, renaming, deleting and directories
  5. Designing classes and creating objects
  6. Accessing and editing attributes
  7. Built-in class attributes
  8. Garbage collection
  9. Key terms
  10. Quick revision
  11. Important questions

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
ComparisonPython file modes
Meaning
If the file exists

'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

1

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())
ModeMeaning
"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) writes
2

Topic 2

File modes, attributes and encoding

Key termsFile modes
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.
3

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).
4

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)
5

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.
6

Topic 6

Built-in class attributes

Key termsBuilt-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}
7

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

  1. Q1.Distinguish modes w and a.
  2. Q2.What does tell() return?
  3. Q3.How is a file deleted in Python?
  4. Q4.What is self?
  5. Q5.Distinguish class and instance attributes.
  6. Q6.How does Python collect garbage?

Long-answer questions

  1. Q1.Explain file handling in Python with programs.
  2. Q2.Explain directory operations with the os module.
  3. Q3.Explain classes and objects with a program.
  4. 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.

WhatsApp us