Python Concepts 16 To 22 Clean
Python Concepts 16 To 22 Clean
Nested Dictionaries
Example:
students = {
"101": {"name": "Divyanshi", "age": 19, "grades": {"Math": 90, "Physics": 85}},
"102": {"name": "Rahul", "age": 20, "grades": {"Math": 78, "Physics": 88}}
}
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!")
a) lower()
- Converts string to all lowercase.
b) upper()
- Converts string to all uppercase.
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
read_specific_lines('example.txt', 2, 4)
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')
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")