Python Programming – 5 Mark Answers
with Detailed Explanation
Q1. Python Program to Find Total Size of All Files in a Given Directory
Theory:
To find the total size of files inside a folder (and its subfolders), we can use:
- os.walk() – loops through all files and folders.
- os.path.getsize() – returns size of a file in bytes.
- os.path.join() – joins folder and filename to get complete path.
Code:
import os
def get_total_size(path):
total = 0
for dirpath, dirnames, filenames in os.walk(path):
for file in filenames:
file_path = os.path.join(dirpath, file)
size = os.path.getsize(file_path)
total += size
return total
print("Total size:", get_total_size("C:/Users/Example"), "bytes")
Explanation:
- os.walk() returns all folders and files.
- os.path.getsize() gives the size of each file.
- Adds all sizes to get the total.
Q2. Indexing and Slicing in Strings
Theory:
Strings in Python are sequences. We can:
- Use indexing to access characters (e.g., text[0])
- Use slicing to extract part of a string (e.g., text[2:5])
Example:
text = "Programming"
print(text[0]) #P
print(text[-1]) # g
print(text[0:6]) # Progra
print(text[::2]) # Pormig
Explanation:
- Indexing uses positive and negative indices.
- Slicing extracts substrings using start:stop:step.
Q3. os Module Methods: getcwd(), chdir(), makedirs()
Theory:
These functions help manage folders in Python:
- getcwd(): Get Current Working Directory
- chdir(path): Change to another directory
- makedirs(): Create nested folders
Code:
import os
print("Current:", os.getcwd())
# os.chdir("C:/NewFolder")
# os.makedirs("Test/Assignments", exist_ok=True)
Q4. Difference Between Absolute and Relative Path
Theory:
Absolute path gives the full location of the file from the root.
Relative path gives the location from the current working directory.
Comparison:
Absolute Path: C:/Users/John/file.txt
Relative Path: docs/file.txt
Absolute is fixed and complete; relative is shorter and more portable.
Q5. Example of Absolute and Relative Path
Code Example:
import os
print("Absolute:", os.path.abspath("data.txt"))
print("Relative: folder/data.txt")
Explanation:
- abspath() converts a relative file name to full path.
- Relative paths are shorter and depend on where the code is running.
Q6. String Methods: isalpha(), isdecimal(), isspace(), istitle(), isalnum()
Theory:
These are used to check string content types.
Examples:
print("Hello".isalpha()) # True
print("123".isdecimal()) # True
print(" ".isspace()) # True
print("My Book".istitle()) # True
print("abc123".isalnum()) # True
Q7. File Reading and Writing in Python
Theory:
Use open() with modes:
- 'r': read
- 'w': write (creates/overwrites)
- 'a': append
- 'r+': read and write
Code:
# Writing
with open("notes.txt", "w") as f:
f.write("This is a Python file.")
# Reading
with open("notes.txt", "r") as f:
content = f.read()
print(content)