Unit 3 Python notes
Unit 3 Python notes
A Python dictionary is a mutable, unordered collection that stores data in key-value pairs.
Each key must be unique, immutable, and hashable (e.g., strings, numbers, tuples), while the
values can be of any data type.
Syntax:
Example:
person = {
"name": "Alice",
"age": 25,
"city": "New York"
}
len(person) # Output: 3
5. update(): Updates the dictionary with key-value pairs from another dictionary or
iterable.
person.update({"gender": "Female"})
person.pop("age") # Output: 25
person.popitem()
person.clear()
new_person = person.copy()
10. setdefault(): Returns the value of a key; if it doesn’t exist, inserts it with a default
value.
person.setdefault("country", "USA")
Dictionary Keys
Example:
Sorting
Sort keys:
Sort by values:
Looping
Nested Dictionaries
Example:
students = {
"student1": {"name": "John", "age": 20},
"student2": {"name": "Jane", "age": 22}
}
A nested function is defined inside another function and can be used for encapsulation or
utility in a dictionary context.
Example:
def outer_function():
def inner_function():
return "Hello, World!"
return inner_function
File Structure
1. Opening a File
The open() function is used to open a file and return a file object. Its syntax is:
Parameters:
Example:
file = open("example.txt", "r")
2. File Modes
Mode Description
'r' Read-only. File must exist.
'w' Write-only. Creates a new file or truncates an existing one.
'x' Exclusive creation. Fails if the file exists.
'a' Append. Writes data at the end of the file.
'b' Binary mode.
't' Text mode (default).
'+' Read and write.
3. Reading Files
File objects provide methods to read data:
read(size): Reads size bytes (or the whole file if size is not specified).
readline(): Reads a single line.
readlines(): Reads all lines into a list.
Example:
file = open("example.txt", "r")
content = file.read()
print(content)
file.close()
4. Writing to Files
File objects also allow writing data:
Example:
file = open("example.txt", "w")
file.write("Hello, World!")
file.close()
5. Closing a File
Always close a file after use to free system resources. Use the close() method:
file.close()
Alternatively, use a context manager (with statement), which automatically closes the file:
6. File Attributes
File objects have attributes that provide additional information:
7. Binary Files
For binary files, use the 'b' mode. Operations read/write raw binary data.
Example:
with open("example.bin", "wb") as file:
file.write(b'\x00\xFF\x10')
Function Description
open() Opens a file and returns a file object.
close() Closes the file.
read() Reads the content of a file.
write() Writes to a file.
readline() Reads a single line from the file.
readlines() Reads all lines from the file into a list.
writelines() Writes a list of lines to a file.
seek() Moves the file pointer to a specific position.
tell() Returns the current position of the file pointer.
flush() Flushes the internal buffer, ensuring data is written to the file.
truncate()
Resizes the file to a specified size.
with statement . Context manager to ensure the file is properly closed after operations
1. open()
Example:
2. close()
file.close()
3. read()
line = file.readline()
5. readlines()
Reads all lines from the file and returns them as a list of strings.
Example:
lines = file.readlines()
6. write()
7. writelines()
8. seek()
file.seek(offset, whence)
Example:
9. tell()
position = file.tell()
10. flush()
Flushes the internal buffer to write data to the disk immediately.
Example:
file.flush()
11. truncate()
import os
os.rename("old.txt", "new.txt")
os.remove("file.txt")
2. pathlib Module
Method Description
file.read(size) Reads at most size characters (or bytes).
file.write(data) Writes data to the file.
file.readlines() Reads all lines into a list.
Method Description
file.seek(offset) Moves the pointer to the given offset.
file.tell() Returns the current file pointer position.
Attribute Description
file.name The name of the file.
file.mode The mode in which the file was opened (r, w, a, etc.).
file.closed Returns True if the file is closed.
file.encoding The encoding of the file (if applicable).
5. Standard Files
Standard files are the three predefined streams available in Python:
Standard Input (stdin): Used to read input from the user (e.g., input()).
Standard Output (stdout): Used to display output (e.g., print()).
Standard Error (stderr): Used to display error messages.
Example:
import sys
# Writing to stdout
sys.stdout.write("Hello, stdout!\n")
# Writing to stderr
sys.stderr.write("An error occurred!\n")
6. Command-Line Arguments
Command-line arguments can be accessed using the sys.argv list. The first element is the
script name, and subsequent elements are the passed arguments.
Example:
import sys
bash
script.py arg1 arg2
Output:
less
Script name: script.py
Arguments: ['arg1', 'arg2']
7. File System
Python provides the os and shutil modules for interacting with the file system.
Common Operations:
Operation Code
Check if a file exists os.path.exists("file.txt")
Get the current directory os.getcwd()
Create a directory os.mkdir("new_dir")
Remove a file os.remove("file.txt")
Rename a file os.rename("old.txt", "new.txt")
Copy a file shutil.copy("src.txt", "dest.txt")
Mode Description
r Read-only mode.
w Write-only mode. Overwrites existing files.
a Append mode. Adds content to the end of the file.
Mode Description
b Binary mode (e.g., rb, wb).
x Exclusive creation mode. Fails if the file exists.