16.
Nested Dictionaries
- A nested dictionary is a dictionary inside another dictionary.
- Useful for storing complex data with multiple layers.
Example:
students = {
"101": {"name": "Divyanshi", "age": 19, "grades": {"Math": 90, "Physics": 85}},
"102": {"name": "Rahul", "age": 20, "grades": {"Math": 78, "Physics": 88}}
}
print(students["101"]["name"]) # Output: Divyanshi
print(students["101"]["grades"]["Math"]) # Output: 90
17. Difference Between Absolute and Relative Paths
Aspect | Absolute Path | Relative Path
----------------|---------------------------------------------|--------------------------------------------
Definition | Complete path from the root or drive letter | Path relative to the current working
directory
Starts with | Root directory (e.g., C:/, /home/) | Current directory or folder (e.g., ./, ../)
Usage | Independent of current directory | Depends on where the program is run
Example | C:/Users/Divyanshi/Documents/file.txt | Documents/file.txt or ../file.txt
18. File Reading and Writing in Python
- Use open() to open a file.
- Mode 'r' for reading, 'w' for writing, 'a' for appending.
- Always close the file or use with statement (context manager) to auto-close.
Reading Example:
with open("example.txt", "r") as file:
content = file.read()
print(content)
Writing Example:
with open("output.txt", "w") as file:
file.write("Hello, world!")
19. String Methods Examples
a) lower()
- Converts string to all lowercase.
print("HELLO".lower()) # Output: hello
b) upper()
- Converts string to all uppercase.
print("hello".upper()) # Output: HELLO
c) islower()
- Checks if all alphabetic characters are lowercase.
print("hello".islower()) # True
print("Hello".islower()) # False
d) isupper()
- Checks if all alphabetic characters are uppercase.
print("HELLO".isupper()) # True
print("Hello".isupper()) # False
20. Reading Specific Lines from a File
You can read specific lines by:
- Reading the entire file and accessing lines by index, or
- Iterating line by line and checking line numbers.
Example: Read specific lines (say lines 2 to 4) from a file
def read_specific_lines(filename, start, end):
with open(filename, 'r') as file:
lines = file.readlines() # Read all lines into a list
# Slice the list to get lines from start to end (1-based indexing)
selected_lines = lines[start-1:end]
for line in selected_lines:
print(line.strip())
read_specific_lines('example.txt', 2, 4)
21. Examples of OS Module Functions
Make sure to import os before using these.
i) os.getcwd()
Returns the current working directory.
import os
print(os.getcwd())
ii) os.chdir(path)
Changes the current working directory to the specified path.
os.chdir('/path/to/directory')
print(os.getcwd()) # Prints the new current directory
iii) os.makedirs(path)
Creates directories recursively. If intermediate directories don't exist, it creates them too.
os.makedirs('parent_dir/child_dir/grandchild_dir')
22. Python Program to Find Total Size of All Files in a Directory
import os
def get_total_size(directory):
total_size = 0
for root, dirs, files in os.walk(directory):
for file in files:
filepath = os.path.join(root, file)
if os.path.isfile(filepath):
total_size += os.path.getsize(filepath)
return total_size
folder = '/path/to/your/directory'
print(f"Total size of files in '{folder}': {get_total_size(folder)} bytes")