29 Python Reference
29.1 Operators
29.1.1 Basic Arithmetic Operators
Arithmetic operators in Python are used to perform mathematical operations on numeric values.
Operator | Description | Example | Result |
---|---|---|---|
+ |
Addition | 5 + 3 |
8 |
- |
Subtraction | 5 - 3 |
2 |
* |
Multiplication | 5 * 3 |
15 |
/ |
Division | 10 / 2 |
5.0 |
// |
Floor Division | 10 // 3 |
3 |
% |
Modulus (Remainder) | 10 % 3 |
1 |
** |
Exponentiation | 2 ** 3 |
8 |
29.1.1.1 Operator Precedence
Remember the order of operations (PEMDAS) when using multiple operators within an expression:
- Parentheses
- Exponents
- Multiplication and Division (from left to right)
- Addition and Subtraction (from left to right)
Example:
- Inside the parentheses:
3 + 4
equals7
. - Exponentiation:
7 ** 2
equals49
. - Multiplication:
2 * 49
equals98
. - Subtraction:
5 - 1
equals4
. - Division:
98 / 4
equals24.5
.
29.1.2 Assignment Operators
Operator | Description | Example | Equivalent |
---|---|---|---|
+= |
Add and Assign | x += 3 |
x = x + 3 |
-= |
Subtract and Assign | x -= 2 |
x = x - 2 |
*= |
Multiply and Assign | x *= 4 |
x = x * 4 |
/= |
Divide and Assign | x /= 2 |
x = x / 2 |
//= |
Floor Divide and Assign | x //= 3 |
x = x // 3 |
%= |
Modulus and Assign | x %= 5 |
x = x % 5 |
**= |
Exponentiation and Assign | x **= 2 |
x = x ** 2 |
29.1.3 Comparison Operators
Comparison operators in Python are used to compare values. They return a Boolean value (True or False) based on whether the comparison is true or false.
29.1.3.1 Numeric Comparison Operators
Operator | Description | Example | Result |
---|---|---|---|
== |
Equal | 5 == 5 |
True |
!= |
Not equal | 5 != 3 |
True |
< |
Less than | 3 < 5 |
True |
> |
Greater than | 5 > 3 |
True |
<= |
Less than or equal to | 3 <= 5 |
True |
>= |
Greater than or equal to | 5 >= 5 |
True |
29.1.3.2 Logical Comparison Operators
Operator | Description | Example | Result |
---|---|---|---|
and |
Logical AND | True and False |
False |
or |
Logical OR | True or False |
True |
not |
Logical NOT | not True |
False |
29.1.3.2.1 Chained Comparisons
Chained comparisons in Python allow you to combine multiple comparisons in a single expression, creating more complex conditions. Comparisons are evaluated from left to right and return a Boolean value (True
or False
) based on whether the entire chain of comparisons is true.
Syntax:
value1 < value2 < value3 # Checks if value1 is less than value2 and value2 is less than value3.
value1 > value2 > value3 # Checks if value1 is greater than value2 and value2 is greater than value3.
value1 <= value2 <= value3 # Checks if value1 is less than or equal to value2 and value2 is less than or equal to value3.
value1 >= value2 >= value3 # Checks if value1 is greater than or equal to value2 and value2 is greater than or equal to value3.
value1 == value2 == value3 # Checks if value1 is equal to value2 and value2 is equal to value3.
value1 != value2 != value3 # Checks if value1 is not equal to value2 and value2 is not equal to value3.
Example:
29.1.3.3 Membership Operators
Operator | Description | Example | Result |
---|---|---|---|
in |
True if value is found in sequence | 5 in [1, 2, 3, 4, 5] |
True |
not in |
True if value is not found in sequence | 6 not in [1, 2, 3, 4, 5] |
True |
29.1.3.4 Identity Operators
Operator | Description | Example | Result |
---|---|---|---|
is |
True if both variables are the same object | x is y |
True |
is not |
True if both variables are not the same object | x is not y |
True |
29.2 Strings
29.2.1 String Comparison Operators
Operator | Description | Example | Result |
---|---|---|---|
== |
Equal | 'hello' == 'world' |
False |
!= |
Not equal | 'hello' != 'world' |
True |
< |
Lexicographically less than | 'abc' < 'def' |
True |
> |
Lexicographically greater than | 'def' > 'abc' |
True |
<= |
Lexicographically less than or equal to | 'abc' <= 'abc' |
True |
>= |
Lexicographically greater than or equal to | 'def' >= 'def' |
True |
29.2.2 String Indexing
s = "Python"
.
Expression | Description | Result |
---|---|---|
s[0] |
Access the first character | "P" |
s[3] |
Access the fourth character | "h" |
s[-1] |
Access the last character | "n" |
s[-3] |
Access the third character from the end | "h" |
s[6] |
Accessing an out-of-range index | Raises an IndexError |
s[-1] |
Accessing an out-of-range negative index | Raises an IndexError |
29.2.3 String Slicing
s = "Python"
.
Expression | Description | Result |
---|---|---|
s[:] |
Slicing to get the entire string | "Python" |
s[0:2] |
Slicing to get a substring | "Py" |
s[2:5] |
Slicing to get a substring | "tho" |
s[:4] |
Slicing from the beginning | "Pyth" |
s[3:] |
Slicing to the end | "hon" |
s[-4:-1] |
Slicing with negative indices | "tho" |
s[::-1] |
Reverse the string | "nohtyP" |
s[::2] |
Get every second character | "Pto" |
s[1::2] |
Get every second character starting from the second character | "yhn" |
s[1:4:2] |
Get every second character from the second to the fourth character | "yh" |
s[4:1:-1] |
Reverse a substring | "oht" |
29.2.4 Scaping Characters
Escape Sequence | Description | Example | Result |
---|---|---|---|
\\ |
Backslash | "C:\\Users\\Alice" |
C:\Users\Alice |
\' |
Single quote | 'It\'s raining' |
It's raining |
\" |
Double quote | "She said, \"Hello!\"" |
She said, "Hello!" |
\n |
Newline | "First line\nSecond line" |
|
\t |
Tab | "First\tSecond" |
First Second |
\b |
Backspace | "Hello\bWorld" |
HellWorld |
29.2.5 String Methods
Method | Description | Example | Result |
---|---|---|---|
upper() |
Converts the string to uppercase | "hello".upper() |
"HELLO" |
lower() |
Converts the string to lowercase | "Hello".lower() |
"hello" |
capitalize() |
Converts the first character to uppercase | "hello".capitalize() |
"Hello" |
title() |
Converts the first character of each word to uppercase | "hello world".title() |
"Hello World" |
strip() |
Removes leading and trailing whitespace | " hello ".strip() |
"hello" |
lstrip() |
Removes leading whitespace | " hello ".lstrip() |
"hello " |
rstrip() |
Removes trailing whitespace | " hello ".rstrip() |
" hello" |
center() |
Centers the string within a specified width | "hello".center(10) |
" hello " |
ljust() |
Left-justifies the string within a specified width | "hello".ljust(10) |
"hello " |
rjust() |
Right-justifies the string within a specified width | "hello".rjust(10) |
" hello" |
ord() |
Returns the Unicode code point of a character | ord("A") |
65 |
chr() |
Returns the character from a Unicode code point | chr(65) |
"A" |
split() |
Splits the string into a list of substrings | "hello world".split() |
["hello", "world"] |
partition() |
Splits the string at the first occurrence of a separator | "hello world".partition(" ") |
("hello", " ", "world") |
join() |
Joins a list of strings into a single string | " ".join(["hello", "world"]) |
"hello world" |
startswith() |
Checks if the string starts with a specified substring | "hello".startswith("he") |
True |
endswith() |
Checks if the string ends with a specified substring | "hello".endswith("lo") |
True |
find() |
Searches for a substring and returns its index | "hello".find("l") |
2 |
replace() |
Replaces a substring with another string | "hello".replace("e", "a") |
"hallo" |
index() |
Searches for a substring and returns its index | "hello".index("l") |
2 |
count() |
Counts the occurrences of a substring | "hello".count("l") |
2 |
len() |
Returns the length of the string | len("hello") |
5 |
isalpha() |
Checks if all characters are alphabetic | "hello".isalpha() |
True |
isdigit() |
Checks if all characters are digits | "123".isdigit() |
True |
isalnum() |
Checks if all characters are alphanumeric | "hello123".isalnum() |
True |
isspace() |
Checks if all characters are whitespace | " ".isspace() |
True |
istitle() |
Checks if the string is titlecased | "Hello World".istitle() |
True |
isupper() |
Checks if all characters are uppercase | "HELLO".isupper() |
True |
islower() |
Checks if all characters are lowercase | "hello".islower() |
True |
int() |
Converts a string to an integer | int("123") |
123 |
float() |
Converts a string to a float | float("3.14") |
3.14 |
str() |
Converts a value to a string | str(123) |
"123" |
29.3 Type Conversion
29.3.1 Implicit Type Conversion
Implicit type conversion, also known as coercion, is the automatic conversion of data types by the Python interpreter.
Data Type | Conversion | Example | Result |
---|---|---|---|
int |
int to float |
x = 10; y = 3.5; z = x + y |
13.5 |
int |
int to str |
x = 10; y = "Number: " + x |
"Number: 10" |
float |
float to str |
x = 3.5; y = "Value: " + x |
"Value: 3.5" |
29.3.2 Explicit Type Conversion
Explicit type conversion, also known as type casting, is the manual conversion of data types using built-in functions.
int()
: Converts to an integer.float()
: Converts to a float.str()
: Converts to a string.bool()
: Converts to a boolean.
Input Example | Output | Description |
---|---|---|
int("10") |
10 |
Convert a string to an integer. |
float("3.14") |
3.14 |
Convert a string to a float. |
str(123) |
"123" |
Convert an integer to a string. |
bool(1) |
True |
Convert an integer to a boolean. |
int(3.5) |
3 |
Convert a float to an integer. |
str(3.5) |
"3.5" |
Convert a float to a string. |
bool(0) |
False |
Convert an integer to a boolean. |
To check the data type of a variable, you can use the type()
function:
29.4 Data Structures
29.4.1 Manipulating Iterables
Data structures in Python, such as lists, tuples, sets, and dictionaries, are iterable objects that can be manipulated using loops and built-in functions.
29.4.1.1 Using enumerate
With enumerate
, you can access both the index (i.e., position) and the item in the iterable.
29.4.1.2 Using zip
With zip
, you can iterate over multiple iterables simultaneously.
If the iterables are of different lengths, zip
stops when the shortest iterable is exhausted.
29.4.2 Lists
List Method | Description | Example | Result |
---|---|---|---|
list.append(element) |
Adds an element to the end of the list. | fruits = ["apple", "banana"]; fruits.append("cherry") |
["apple", "banana", "cherry"] |
list.insert(index, element) |
Inserts an element at the specified index. | fruits = ["apple", "banana"]; fruits.insert(1, "cherry") |
["apple", "cherry", "banana"] |
list.remove(element) |
Removes the first occurrence of the specified element from the list. | fruits = ["apple", "banana", "cherry"]; fruits.remove("banana") |
["apple", "cherry"] |
list.pop(index) |
Removes the element at the specified index (or the last element if no index is specified) and returns it. | fruits = ["apple", "banana", "cherry"]; fruits.pop(1) |
["apple", "cherry"] |
list.index(element) |
Returns the index of the first occurrence of the specified element in the list. | ["apple", "banana", "cherry"].index("banana") |
1 |
element in list |
Returns True if the element is present in the list, False otherwise. |
"banana" in ["apple", "banana", "cherry"] |
True |
list.count(element) |
Returns the number of occurrences of the specified element in the list. | ["apple", "banana", "cherry", "banana"].count("banana") |
2 |
list.sort() |
Sorts the elements of the list in ascending order. | fruits = ["banana", "apple", "cherry"]; fruits.sort() |
["apple", "banana", "cherry"] |
list.reverse() |
Reverses the order of the elements in the list. | fruits = ["apple", "banana", "cherry"]; fruits.reverse() |
["cherry", "banana", "apple"] |
list.copy() |
Returns a copy of the list. | fruits = ["apple", "banana", "cherry"]; fruits_copy = fruits.copy() |
["apple", "banana", "cherry"] |
list.clear() |
Removes all elements from the list. | fruits = ["apple", "banana", "cherry"]; fruits.clear() |
[] |
len(list) |
Returns the number of elements in the list. | len(["apple", "banana", "cherry"]) |
3 |
max(list) |
Returns the maximum element in the list. | max([3, 1, 4, 1, 5, 9, 2, 6, 5]) |
9 |
min(list) |
Returns the minimum element in the list. | min([3, 1, 4, 1, 5, 9, 2, 6, 5]) |
1 |
sum(list) |
Returns the sum of all elements in the list. | sum([1, 2, 3, 4, 5]) |
15 |
sorted(list) |
Returns a new list with the elements of the original list sorted. | sorted([3, 1, 4, 1, 5, 9, 2, 6, 5]) |
[1, 1, 2, 3, 4, 5, 5, 6, 9] |
list.extend(iterable) |
Extends the list by appending elements from the iterable. | fruits = ["apple", "banana"]; fruits.extend(["cherry", "orange"]) |
["apple", "banana", "cherry", "orange"] |
sorted(list, key=function) |
Returns a new list with the elements of the original list sorted using the specified key function. | sorted(["apple", "banana", "cherry"], key=len) |
["apple", "cherry", "banana"] |
reversed(list) |
Returns an iterator that iterates over the elements of the list in reverse order. | list(reversed(["apple", "banana", "cherry"])) |
["cherry", "banana", "apple"] |
29.4.3 Sets
s = {1, 2, 3, 4, 5}
.
Set Method | Description | Example | Result |
---|---|---|---|
set.add(element) |
Adds an element to the set. | s.add(6) |
{1, 2, 3, 4, 5, 6} |
set.remove(element) |
Removes an element from the set. Raises an error if the element is not present. | s.remove(3) |
{1, 2, 4, 5} |
set.discard(element) |
Removes an element from the set if it is present. Does not raise an error if the element is not present. | s.discard(3) |
{1, 2, 4, 5} |
set.pop() |
Removes and returns an arbitrary element from the set. Raises an error if the set is empty. | s.pop() |
1 |
set.clear() |
Removes all elements from the set. | s.clear() |
set() |
len(set) |
Returns the number of elements in the set. | len(s) |
5 |
element in set |
Returns True if the element is present in the set, False otherwise. |
2 in s |
True |
set.union(other) |
Returns a new set with elements from both sets. | s.union({4, 5, 6}) |
{1, 2, 3, 4, 5, 6} |
set.intersection(other) |
Returns a new set with elements common to both sets. | s.intersection({3, 4, 5, 6}) |
{3, 4, 5} |
set.difference(other) |
Returns a new set with elements in the set but not in the other set. | s.difference({3, 4}) |
{1, 2, 5} |
set.symmetric_difference(other) |
Returns a new set with elements in either set but not in both sets. | s.symmetric_difference({4, 5, 6}) |
{1, 2, 3, 6} |
set.issubset(other) |
Returns True if the set is a subset of the other set. |
s.issubset({1, 2, 3, 4, 5, 6}) |
True |
set.issuperset(other) |
Returns True if the set is a superset of the other set. |
s.issuperset({1, 2, 3}) |
True |
29.4.4 Dictionaries
Dictionary Example | Description |
---|---|
{"name": "Alice", "age": 30} |
A dictionary with string keys and values. |
{1: "apple", 2: "banana"} |
A dictionary with integer keys and string values. |
{("x", "y"): 10, ("a", "b"): 20} |
A dictionary with tuple keys and integer values. |
{"name": "Alice", "address": {"city": "New York", "zip": 10001}} |
A dictionary with a nested dictionary as a value. |
{} |
An empty dictionary. |
29.4.4.1 Dictionary Methods
d = {"name": "Alice", "age": 30, "city": "New York"}
.
Dictionary Method | Description | Example | Result |
---|---|---|---|
dict.keys() |
Returns a view of the keys in the dictionary. | d.keys() |
dict_keys(["name", "age", "city"]) |
dict.values() |
Returns a view of the values in the dictionary. | d.values() |
dict_values(["Alice", 30, "New York"]) |
dict.items() |
Returns a view of the key-value pairs in the dictionary. | d.items() |
dict_items([("name", "Alice"), ("age", 30), ("city", "New York")]) |
dict.get(key) |
Returns the value associated with the key, or None if the key is not found. |
d.get("name") |
"Alice" |
dict.get(key, default) |
Returns the value associated with the key, or the default value if the key is not found. | d.get("address", "Unknown") |
"Unknown" |
dict.pop(key) |
Removes the key and returns the value associated with the key. | d.pop("age") |
30 |
dict.popitem() |
Removes and returns an arbitrary key-value pair from the dictionary. | d.popitem() |
("city", "New York") |
dict.update(other) |
Updates the dictionary with key-value pairs from another dictionary or iterable. | d.update({"city": "Los Angeles"}) |
{"name": "Alice", "city": "Los Angeles"} |
dict.clear() |
Removes all key-value pairs from the dictionary. | d.clear() |
{} |
len(dict) |
Returns the number of key-value pairs in the dictionary. | len(d) |
3 |
key in dict |
Returns True if the key is present in the dictionary, False otherwise. |
"name" in d |
True |
del dict[key] |
Removes the key and its associated value from the dictionary. | del d["age"] |
{"name": "Alice", "city": "New York"} |
29.4.4.2 Dictionary Comprehension
Dictionary Comprehension | Description | Example | Result |
---|---|---|---|
{key: value for key, value in dictionary.items()} |
Applies the expression to each key-value pair in the dictionary. | {k: v*2 for k, v in {"a": 1, "b": 2}.items()} |
{"a": 2, "b": 4} |
{key: value for key, value in dictionary.items() if condition} |
Applies the expression to each key-value pair that satisfies the condition. | {k: v*2 for k, v in {"a": 1, "b": 2}.items() if v > 1} |
{"b": 4} |
{key: expression for key in keys} |
Applies the expression to each key in the list of keys. | {k: k*2 for k in ["a", "b"]} |
{"a": "aa", "b": "bb"} |
{key: expression for key in keys if condition} |
Applies the expression to each key that satisfies the condition. | {k: k*2 for k in ["a", "b"] if k == "b"} |
{"b": "bb"} |
29.4.5 Tuples
Tuple Example | Description |
---|---|
("apple", "banana", "cherry") |
A tuple of strings. |
(1, 2, 3, 4, 5) |
A tuple of integers. |
("apple", 1, "banana", 2) |
A tuple of mixed data types. |
("apple", ("banana", "cherry"), "orange") |
A tuple with a nested tuple. |
() |
An empty tuple. |
((1, 2), (3, 4), (5, 6)) |
A 2D tuple with three rows and two columns. |
(1,) |
A tuple with a single element. Note the comma , after the element. |
t = (1, 2, 3, 1, 2)
.
Tuple Method | Description | Example | Result |
---|---|---|---|
tuple.count(element) |
Returns the number of occurrences of the specified element in the tuple. | t.count(1) |
2 |
tuple.index(element) |
Returns the index of the first occurrence of the specified element in the tuple. | t.index(2) |
1 |
len(tuple) |
Returns the number of elements in the tuple. | len(t) |
5 |
max(tuple) |
Returns the maximum element in the tuple. | max(t) |
3 |
min(tuple) |
Returns the minimum element in the tuple. | min(t) |
1 |
sum(tuple) |
Returns the sum of elements in the tuple. | sum(t) |
9 |
sorted(tuple) |
Returns a list with the elements of the original tuple sorted. | tuple(sorted(t)) |
(1, 1, 2, 2, 3) |
reversed(tuple) |
Returns an iterator that iterates over the elements of the tuple in reverse order. | tuple(reversed(t)) |
(2, 1, 3, 2, 1) |
29.5 Classes
29.5.1 Class Definition
29.5.2 Creating an Instance of a Class
29.5.3 Using Class Attributes
29.6 Conditional Statements
29.6.1 If Statement
29.6.2 If-Else Statement
29.6.3 If-Elif-Else Statement
29.6.4 Nested If Statements
29.6.5 Match Statement (Python 3.10+)
29.7 Loops
29.7.1 For Loop
29.7.1.1 Basic For Loop
29.7.1.2 Using range
29.7.1.3 Using continue
29.7.1.4 Using break
29.7.2 While Loop
29.7.2.1 Basic While Loop
29.7.2.2 Using continue
29.7.2.3 Using break
29.8 Python Pandas Reference
To use the pandas library in Python, you need to import it using the following statement:
29.8.1 Creating DataFrames
29.8.1.1 From Dictionary
29.8.1.2 From List of Lists
29.8.1.3 From NumPy Array
29.8.1.4 From CSV File
29.8.2 Basic Data Inspection
Method | Description | Example |
---|---|---|
df.head(n) |
Returns the first n rows of the DataFrame. Defaults to 5 if n is not specified. |
df.head(3) |
df.tail(n) |
Returns the last n rows of the DataFrame. Defaults to 5 if n is not specified. |
df.tail(3) |
df.info() |
Provides a concise summary of the DataFrame, including column types and non-null counts. | df.info() |
df.describe() |
Generates summary statistics for numerical columns. | df.describe() |
df.shape |
Returns the dimensions of the DataFrame (rows, columns). | df.shape |
df.columns |
Returns the column labels of the DataFrame. | df.columns |
df.index |
Returns the row labels of the DataFrame. | df.index |
29.8.3 Handling Missing Values
Method | Description | Example |
---|---|---|
df.isnull() |
Checks for missing values, returning a DataFrame of True /False . |
df.isnull() |
df.fillna(value) |
Fills missing values (NaN ) with the specified value. |
df.fillna(0) |
df.dropna() |
Removes rows or columns with missing values. | df.dropna() |
df.drop_duplicates() |
Removes duplicate rows from the DataFrame. | df.drop_duplicates() |
29.8.4 Data Selection & Filtering
Method | Description | Example |
---|---|---|
df['col'] |
Accesses a specific column from the DataFrame. | df['Age'] |
df[['col1', 'col2']] |
Accesses multiple specific columns. | df[['Name', 'Age']] |
df.loc[row, col] |
Accesses rows and columns by labels. | df.loc[0, 'Name'] |
df.iloc[row, col] |
Accesses rows and columns by index positions. | df.iloc[0, 1] |
df[df['col'] > value] |
Filters rows based on a condition. | df[df['Sales'] > 200] |
df[df['col'].isin(values)] |
Filters rows based on a list of values. | df[df['City'].isin(['New York', 'Chicago'])] |
df.query('condition') |
Filters rows based on a query condition. | df.query('Sales > 200') |
29.8.5 Data Manipulation
Method | Description | Example |
---|---|---|
df.rename(columns=...) |
Renames column(s). | df.rename(columns={'Age':'Years'}) |
df.sort_values(by=...) |
Sorts the DataFrame by column(s). | df.sort_values(by='Age') |
df.groupby(...) |
Groups the DataFrame and applies functions. | df.groupby('City').mean() |
df.apply(func) |
Applies a function to rows or columns. | df['Age'].apply(lambda x:x + 1) |
df.astype(type) |
Converts the data type of a column. | df['Age'].astype(str) |
df.copy() |
Returns a copy of the DataFrame. | df.copy() |
29.8.6 Indexing & Reshaping
Method | Description | Example |
---|---|---|
df.set_index(...) |
Sets a column as the index. | df.set_index('ID') |
df.reset_index() |
Resets the index. | df.reset_index() |
df.pivot(index=..., columns=..., values=...) |
Reshapes the DataFrame. | df.pivot(index='ID', columns='City', values='Sales') |
df.melt(id_vars=..., value_vars=...) |
Converts wide format to long format. | df.melt(id_vars='ID', value_vars=['Age', 'Sales']) |
29.8.7 Merging & Concatenation
Method | Description | Example |
---|---|---|
df.merge(df2, on='col') |
Merges two DataFrames based on a common column. | df.merge(df2, on='ID') |
pd.concat([df1, df2]) |
Concatenates multiple DataFrames along an axis. | pd.concat([df, df2]) |
29.8.8 Exporting & Importing Data
Method | Description | Example |
---|---|---|
df.to_csv('file.csv') |
Saves the DataFrame to a CSV file. | df.to_csv('output.csv') |
df.to_excel('file.xlsx') |
Saves the DataFrame to an Excel file. | df.to_excel('output.xlsx') |
pd.read_csv('file.csv') |
Reads a CSV file into a DataFrame. | df = pd.read_csv('data.csv') |
pd.read_excel('file.xlsx') |
Reads an Excel file into a DataFrame. | df = pd.read_excel('data.xlsx') |
29.9 File Manipulation
29.9.1 Opening Files
Method | Description | Example |
---|---|---|
open(path, mode) |
Opens a file in the specified mode (e.g., read 'r' , write 'w' ). |
f = open('file.txt', 'w') |
with open(path, mode) |
Context manager to safely open and close files. | with open('file.txt', 'r') as f: content = f.read() |
file.close() |
Closes the file after operations. | file.close() |
29.9.2 Reading Files
Method | Description | Example |
---|---|---|
file.read() |
Reads the entire contents of the file. | content = file.read() |
file.readlines() |
Reads all lines from the file and returns them as a list. | lines = file.readlines() |
file.readline() |
Reads a single line from the file. | line = file.readline() |
29.9.3 Writing Files
file
refers to an open file object.
Method | Description | Example |
---|---|---|
file.write(data) |
Writes data to the file (overwrites in write mode 'w' ). |
file.write('Hello') |
file.writelines(lines) |
Writes a list of lines to the file. | file.writelines(['Line1\n', 'Line2\n']) |
29.9.4 Checking File Properties (Using os
)
Method | Description | Example |
---|---|---|
os.path.exists(path) |
Checks if a path exists. | os.path.exists('file.txt') |
os.path.isfile(path) |
Checks if the path is a file. | os.path.isfile('file.txt') |
os.path.isdir(path) |
Checks if the path is a directory. | os.path.isdir('folder') |
os.path.getsize(path) |
Gets the size of a file in bytes. | os.path.getsize('file.txt') |
29.9.5 Managing Files and Directories (Using os
and shutil
)
Method | Description | Example |
---|---|---|
os.listdir(path) |
Lists all files and directories in a given path. | os.listdir('folder') |
os.makedirs(path, exist_ok=True) |
Creates directories and their parents if needed. | os.makedirs('folder/subfolder', exist_ok=True) |
shutil.copy(src, dst) |
Copies a file from src to dst . |
shutil.copy('file.txt', 'copy.txt') |
shutil.move(src, dst) |
Moves or renames a file or directory. | shutil.move('file.txt', 'new_folder/file.txt') |
os.remove(path) |
Deletes a file. | os.remove('file.txt') |
os.rmdir(path) |
Deletes an empty directory. | os.rmdir('empty_folder') |
shutil.rmtree(path) |
Deletes a directory and all its contents. | shutil.rmtree('folder') |
29.9.6 Path Manipulation (Using pathlib
)
pathlib
module in Python.
Method | Description | Example |
---|---|---|
Path(path).exists() |
Checks if the path exists. | Path('file.txt').exists() |
Path(path).is_file() |
Checks if the path is a file. | Path('file.txt').is_file() |
Path(path).is_dir() |
Checks if the path is a directory. | Path('folder').is_dir() |
Path(path).unlink() |
Deletes a file. | Path('file.txt').unlink() |
Path(path).mkdir(parents=True) |
Creates a directory, including any parent directories. | Path('folder/subfolder').mkdir(parents=True) |
Path().cwd() |
Gets the current working directory. | Path().cwd() |
Path.home() |
Gets the home directory of the user. | Path.home() |
Path(path).parent |
Gets the parent directory of the path. | Path('folder/file.txt').parent → Path('folder') |
Path(path).name |
Gets the file name with extension. | Path('folder/file.txt').name → 'file.txt' |
Path(path).stem |
Gets the file name without extension. | Path('folder/file.txt').stem → 'file' |
Path(path).suffix |
Gets the file extension. | Path('folder/file.txt').suffix → '.txt' |
Path(path).anchor |
Gets the root of the path. | Path('/home/user/file.txt').anchor → '/' |
Path(path).parts |
Returns the path as a tuple of components. | Path('folder/subfolder/file.txt').parts → ('folder', 'subfolder', 'file.txt') |