Tuesday, September 29, 2026

Python file-handling

 ### Top 20 Python `open()` Function Quiz 🐍


Test your Python file-handling knowledge with 20 multiple-choice questions covering file modes, reading, writing, appending, `with` statements, and file pointers.


### Part 1: Basic `open()` Quiz

Q1. What is the default mode of open()?

A. 'w'

B. 'r'

C. 'a'

D. 'x'

Correct answer: B

The default mode is 'r', which opens a file for reading.


Q2. What happens if you open a non-existing file using open('test.txt', 'r')?

A. Creates the file

B. Returns None

C. Raises FileNotFoundError

D. Creates an empty file

Correct answer: C

Read mode requires the file to exist.


Q3. Which mode opens a file for writing and truncates existing content?

A. 'a'

B. 'r'

C. 'w'

D. 'x'

Correct answer: C

'w' creates a file if needed and clears existing content.


Q4. Which mode adds content to the end of a file?

A. 'r'

B. 'a'

C. 'w'

D. 'x'

Correct answer: B

Append mode writes at the end without removing existing content.


Q5. What does mode 'x' do?

A. Reads a file

B. Appends content

C. Creates a new file exclusively

D. Deletes a file

Correct answer: C

'x' raises FileExistsError if the file already exists.


Q6. What does file.read() return?

A. A list of lines

B. A string containing file content

C. A file object

D. An integer

Correct answer: B

read() returns the file contents as a string in text mode.


Q7. What does readline() return?

A. All lines

B. One line, including newline if present

C. A list

D. The last line only

Correct answer: B

readline() reads one line at a time.


Q8. What does readlines() return?

A. A string

B. A tuple

C. A list of lines

D. A dictionary

Correct answer: C

readlines() returns a list where each element is a line.


Q9. Which method writes a string to a file?

A. read()

B. write()

C. readline()

D. append()

Correct answer: B

write() writes a string and does not automatically add a newline.


Q10. What is the purpose of the with statement when opening files?

A. Makes file read-only

B. Automatically closes the file

C. Deletes the file

D. Opens only binary files

Correct answer: B

The context manager closes the file automatically, even if an exception occurs.


### Part 2: Output-Based Quiz

Q11. What is printed if file.txt contains Hello World?

f = open('file.txt', 'r') print(f.read(5))

A. Hello

B. Hello World

C. World

D. Error

Correct answer: A

read(5) reads the first five characters.


Q12. What is printed if file.txt contains Python?

f = open('file.txt', 'r') print(f.read()) print(f.read())

A. Python twice

B. Python followed by a blank line

C. Error

D. None twice

Correct answer: B

The first read consumes the content. The second read returns an empty string.


Q13. What is the content after execution if file.txt initially contains ABC?

f = open('file.txt', 'w') f.write('XYZ') f.close()

A. ABCXYZ

B. ABC

C. XYZ

D. XYZABC

Correct answer: C

Write mode truncates the original file before writing XYZ.


Q14. If file.txt contains Hi, what is its content after this?

f = open('file.txt', 'a') f.write('!') f.close()

A. !

B. Hi!

C. Hi

D. !Hi

Correct answer: B

Append mode adds ! at the end.


Q15. What does this print?

with open('file.txt', 'w') as f: f.write('Python') print(f.closed)

A. False

B. True

C. Python

D. Error

Correct answer: B

The with block closes the file when execution exits the block.


Q16. What is printed?

f = open('file.txt', 'w') print(f.write('Hello')) f.close()

A. Hello

B. 5

C. None

D. True

Correct answer: B


write() returns the number of characters written. Hello has five characters.


Q17. What is printed?

f = open('file.txt', 'w') f.write('ABC\\nDEF') f.close() f = open('file.txt', 'r') print(f.readline().strip())

A. ABC

B. DEF

C. ABC DEF

D. ABC\\nDEF

Correct answer: A

readline() reads the first line; strip() removes the newline.


Q18. What does seek(0) do?

f.seek(0)

A. Closes the file

B. Moves the file pointer to the beginning

C. Deletes the first character

D. Moves to the end

Correct answer: B

seek(0) moves the file pointer to byte/character position zero in ordinary text-file usage.


Q19. What is printed?

f = open('file.txt', 'w+') f.write('ABC') f.seek(0) print(f.read()) f.close()

A. ABC

B. Empty string

C. 3

D. Error

Correct answer: A

w+ permits reading and writing. seek(0) moves the pointer back to the beginning.


Q20. What happens when opening an existing file with mode 'x'?

f = open('existing.txt', 'x')

A. File is overwritten

B. File is appended

C. FileExistsError is raised

D. File is read

Correct answer: C

Exclusive creation fails if the file already exists.


### Quick revision: Python file modes


| Mode | Purpose |

| ---- | ---------------------------------------- |

| r | Read; file must exist |

| w | Write; truncates existing content |

| a | Append; creates file if missing |

| x | Create exclusively; fails i

f file exists |

| r+ | Read and write; file must exist |

| w+ | Read and write; truncates existing file |

| a+ | Read and append; creates if missing |


Remember: Use `with open("file.txt", "r") as f:` for automatic file closing.

Classes, Objects, Inheritance, Method Overriding & More

 ### Top 20 Python OOP Quiz 🐍


### Classes, Objects, Inheritance, Method Overriding & More


Test your Python knowledge with these 20 output-based MCQs covering classes, constructors, inheritance, method overriding, `super()`, polymorphism, encapsulation, and abstraction.


### Section 1: Classes and Objects

Q1. What is the output?

```python

class Student:

    def __init__(self, name):

        self.name = name


s = Student("Ravi")

print(s.name)

```

A. Student

B. Ravi

C. name

D. Error

Answer: B — Ravi. `self.name` stores the instance attribute.


Q2. What is the output?

```python

class Demo:

    x = 10


a = Demo()

b = Demo()

a.x = 20


print(b.x)

```


A. 10

B. 20

C. None

D. Error

Answer: A — 10. Assigning `a.x` creates an instance attribute; `b.x` still resolves to the class attribute.


Q3. What does `__init__()` do?

A. Destroys an object

B. Initializes an instance after it is created

C. Inherits a class

D. Defines a static method

Answer: B — It initializes the newly created instance.


Q4. What is the output?

```python

class A:

    def show(self):

        print("A")


obj = A()

obj.show()

```

A. A

B. show

C. None

D. Error

Answer: A — A.


Q5. What is the output?

```python

class Counter:

    count = 0


    def __init__(self):

        Counter.count += 1


a = Counter()

b = Counter()

print(Counter.count)

```

A. 0

B. 1

C. 2

D. Error

Answer: C — 2. The class variable is incremented for each instance.


### Section 2: Inheritance and Method Overriding

Q6. What is the output?

```python

class Parent:

    def show(self):

        print("Parent")


class Child(Parent):

    pass


Child().show()

```

A. Child

B. Parent

C. None

D. Error

Answer: B — Parent. Child inherits the method.


Q7. What is the output?

```python

class Parent:

    def show(self):

        print("Parent")


class Child(Parent):

    def show(self):

        print("Child")


Child().show()

```

A. Parent

B. Child

C. Parent Child

D. Error

Answer: B — Child. The child overrides the parent method.


Q8. What is the output?

```python

class A:

    def show(self):

        print("A")


class B(A):

    def show(self):

        super().show()

        print("B")


B().show()

```

A. B then A

B. A then B

C. B only

D. Error

Answer: B — A, then B. `super()` calls the next implementation in the method resolution order.


Q9. What is the output?

```python

class A:

    def __init__(self):

        print("A")


class B(A):

    def __init__(self):

        print("B")


B()

```

A. A then B

B. B then A

C. B only

D. A only

Answer: C — B only. The child constructor does not call the parent constructor.


Q10. What is the output?

```python

class A:

    def __init__(self):

        self.x = 10


class B(A):

    def __init__(self):

        super().__init__()

        self.y = 20


obj = B()

print(obj.x + obj.y)

```

A. 10

B. 20

C. 30

D. Error

Answer: C — 30. `super().__init__()` initializes `x`; the child initializes `y`.


Q11. Which inheritance type allows a class to inherit from two parent classes?

A. Single inheritance

B. Multiple inheritance

C. Multilevel inheritance

D. Hierarchical inheritance

Answer: B — Multiple inheritance.


Q12. What is the output?

```python

class A:

    def show(self):

        print("A")


class B:

    def show(self):

        print("B")


class C(A, B):

    pass


C().show()

```

A. A

B. B

C. A B

D. Error

Answer: A — A. Python searches base classes according to the MRO; A comes first.


### Section 3: Polymorphism, Encapsulation & Abstraction

Q13. What is the output?

```python

class Animal:

    def sound(self):

        print("Animal")


class Dog(Animal):

    def sound(self):

        print("Bark")


def make_sound(obj):

    obj.sound()


make_sound(Dog())

```

A. Animal

B. Bark

C. Both

D. Error

Answer: B — Bark. This demonstrates runtime polymorphism.


Q14. What is the output?

```python

class A:

    def show(self):

        return "Hello"


obj = A()

print(obj.show())

```

A. None

B. Hello

C. show

D. Error

Answer: B — Hello. The method returns a string.


Q15. What is the output?

```python

class Employee:

    def __init__(self):

        self.__salary = 50000


e = Employee()

print(e.__salary)

```

A. 50000

B. None

C. AttributeError

D. SyntaxError

Answer: C — AttributeError. Double-underscore attributes undergo name mangling.


Q16. What is the output?

```python

class A:

    def __init__(self):

        self.__x = 10


obj = A()

print(obj._A__x)

```

A. 10

B. None

C. AttributeError

D. SyntaxError

Answer: A — 10. Name mangling changes `__x` to `_A__x`; it is not strict privacy.


Q17. Which module provides support for abstract base classes?

A. os

B. abc

C. sys

D. math

Answer: B — `abc` (Abstract Base Classes).


Q18. What happens when you run this code?

```python

from abc import ABC, abstractmethod


class Shape(ABC):

    @abstractmethod

    def area(self):

        pass


s = Shape()

```

A. Object created successfully

B. Returns None

C. TypeError

D. SyntaxError

Answer: C — TypeError. A class with unimplemented abstract methods cannot be instantiated.


Q19. What is the output?

```python

class A:

    def greet(self):

        print("Hello")


class B(A):

    pass


class C(B):

    pass


C().greet()

```

A. Hello

B. A

C. None

D. Error

Answer: A — Hello. This is multilevel inheritance: A → B → C.


Q20. What is the output?

```python

class A:

    def show(self):

        print("A")


class B(A):

    def show(self):

        print("B")

        super().show()


class C(B):

    def show(self):

        print("C")

        super().show()


C().show()

```

A. A B C

B. C B A

C. C A B

D. C only

Answer: B — C, B, A. Each `super()` call invokes the next method in the MRO.


### Quick Revision – Python OOP


| Concept | Key point |

| ------------- | ---------------------------------------------------------------------- |

| Class | Blueprint for creating objects |

| Object | Instance of a class |

| Inheritance | Reuse parent class functionality |

| Overriding | Child provides its own implementation of an inherited method |

| super() | Accesses the next implementation in the MRO |

| Polymorphism | Same interface, different behavior |

| Encapsulation | Bundling data and methods; name mangling helps avoid accidental access |

| Abstraction | Define required interfaces using abstract classes and methods |

Tuesday, September 22, 2026

Linux df and du commands to manage and check disk space


1. df (Disk Free) — Check Filesystem Space

The df command shows the amount of disk space available on the entire file system.

  • Basic usage (Human-readable format):

    Bash
    df -h
    
    (The -h flag converts bytes into KB, MB, or GB for readability).

  • Show filesystem types along with space:

    Bash
    df -Th
    
    (Displays formats like ext4, tmpfs, xfs, etc.)

  • Check Inode usage (file count limits):

    Bash
    df -i
    
    (Useful if your disk says it has space, but you get "No space left on device" errors due to running out of inodes).

2. du (Disk Usage) — Check File & Directory Sizes

The du command estimates file and directory space usage, helping you find which specific folders are consuming your storage.

  • Check the size of a specific directory (human-readable):

    Bash
    du -sh /path/to/directory
    
    (The -s flag gives a summary total instead of listing every individual sub-file).

  • List sizes of all files and subfolders in the current directory:

    Bash
    du -h --max-depth=1
    
    (Helps you quickly see which sub-folder is taking up the most space).

  • Sort directories by size (largest first):

    Bash
    du -h --max-depth=1 | sort -hr
    
  • Show total size of everything in the current directory including a grand total:
    Bash
    du -ch
    


💡 Quick Summary Comparison

CommandFocusBest Used ForCommon Flag
dfFilesystem levelChecking overall hard drive / partition capacitydf -h
duDirectory levelFinding which specific folders or files are hogging spacedu -sh *