Modules and Packages in Python
In Python, both packages and modules are
used for organizing and structuring code, but they serve different purposes.
A module is a single file that contains
Python code. It can define functions, classes, and variables that can be
used in other parts of the code. You can import a module into another module or
into the Python shell using the import statement.
A package is a collection of modules.
It is a directory that contains a special file called __init__.py which
tells Python that the directory should be treated as a package. A package can
contain other packages or modules, which can be imported in a similar way to
modules.
key
differences between packages and modules:
·
A module is a single file,
while a package is a directory that can contain multiple files (modules).
·
Modules are used to organize
code within a single file, while packages are used to organize modules into a
hierarchical directory structure.
·
Packages provide a way to
namespace modules, which helps to prevent naming conflicts and makes it easier
to organize large projects.
·
Packages can have their own
sub-packages, which can contain additional modules or sub-packages.
·
To use a module, you simply
import it using the import statement. To use a package, you import modules from
the package using dot notation (e.g. import mypackage.mymodule).
re Module
re is a
Python module, short for "regular expression". It is a
built-in module in Python and provides support for regular expressions. Regular
expressions are a powerful tool for manipulating strings and matching patterns
in text. The re module in Python provides a set of functions that can be used
to perform various operations on strings using regular expressions, including
searching, replacing, and splitting strings.
In Summary:
·
The re module in Python
provides support for regular expressions (RE) and allows us to work with
strings in a more advanced way.
·
Regular expressions are
patterns that can be used to match specific characters or sequences of
characters in a string.
Importing
re Module:
·
The first step in using the re
module is to import it into your Python script by using the following code:
import re
Methods and Functions:
match()
This method searches for a pattern at the beginning of a string. If
the pattern is found, it returns a match object. Otherwise, it returns None.
re.match(pattern,
string, flags=0)
search()
This method searches for a pattern anywhere in the string. If the
pattern is found, it returns a match object. Otherwise, it returns None.
re.search(pattern,
string, flags=0)
findall()
This method returns a list of all non-overlapping matches in the
string. If the pattern is not found, it returns an empty list.
re.findall(pattern,
string, flags=0)
sub()
This method replaces all occurrences of the pattern in the string
with a specified string.
re.sub(pattern,
repl, string, count=0, flags=0)
split()
This method splits a string into a list of substrings based on a
specified pattern.
re.split(pattern,
string, maxsplit=0, flags=0)
compile()
This method compiles a regular expression pattern into a regular
expression object.
re.compile(pattern,
flags=0)
Regular Expression Patterns:
^ - Matches the
beginning of a string.
$ - Matches the end of
a string.
. - Matches any
character except a newline.
[] - Matches any
character within the brackets.
[^] - Matches any
character not within the brackets.
. . Matches zero or
more occurrences of the preceding pattern.
. . Matches one or more
occurrences of the preceding pattern.
? - Matches zero or one
occurrence of the preceding pattern.
{m,n} - Matches m to n
occurrences of the preceding pattern.
() - Groups patterns
together.
Flags:
re.IGNORECASE or re.I -
Makes matching case-insensitive.
re.MULTILINE or re.M -
Allows matching of the beginning or end of each line.
re.DOTALL or re.S -
Makes the . character match any character, including newlines.
re.VERBOSE or re.X -
Allows the use of whitespace and comments within the pattern.
Examples:
Match a pattern at the beginning of a string.
import re
pattern = "^Hello"
string = "Hello World"
if re.match(pattern, string):
print("Pattern found!")
else:
print("Pattern not found!")
Output:
Pattern found!
Search for a pattern anywhere in a string.
import re
pattern = "World"
string = "Hello World"
if re.search(pattern, string):
print("Pattern found!")
else:
print("Pattern not found!")
Output:
Pattern found!
Replace all occurrences of a pattern in a string.
import re
pattern = "World"
string = "Hello World"
new_string = re.sub(pattern, "Universe", string)
print(new_string)
Output:
Hello Universe
Split a string into a list of substrings based on a pattern.
import re
pattern = " "
string = "Hello World"
substrings = re.split(pattern, string)
print(substrings)
Output:
['Hello', 'World']
os Module
The os module in Python provides a way of using operating
system-dependent functionality like reading or writing to the file system,
accessing environment variables, and working with processes.
Importing the os module:
import os
Current working directory:
The os module provides a way to get the
current working directory using the getcwd() function. This function
returns a string containing the absolute path of the current working directory.
current_dir
= os.getcwd()
Creating directories:
The os module provides a way to create
directories using the mkdir() function. This function takes a single
argument, which is the name of the directory to be created.
os.mkdir("new_directory")
Checking if a file or directory exists:
The os module provides a way to check if a
file or directory exists using the exists() function. This function
takes a single argument, which is the path of the file or directory to be
checked. It returns True if the file or directory exists, and False otherwise.
#
Check if a file exists
file_exists
= os.path.exists("myfile.txt")
#
Check if a directory exists
dir_exists
= os.path.exists("mydirectory")
Joining paths:
The os module provides a way to join two
or more path components using the join() function. This function takes
multiple arguments, which are the path components to be joined, and returns a
string containing the joined path.
path
= os.path.join("path", "to", "file.txt")
List directory contents:
The os module provides a way to list the
contents of a directory using the listdir() function. This function
takes a single argument, which is the path of the directory to be listed. It
returns a list containing the names of the files and directories in the
specified directory.
dir_contents
= os.listdir("mydirectory")
Renaming files or directories:
The os module provides a way to rename
files or directories using the rename() function. This function takes
two arguments, which are the current name and the new name of the file or
directory.
#
Rename a file
os.rename("old_file.txt",
"new_file.txt")
#
Rename a directory
os.rename("old_directory",
"new_directory")
Deleting files or directories:
The os module provides a way to delete
files or directories using the remove() and rmdir() functions,
respectively. The remove() function takes a single argument, which is the path
of the file to be deleted. The rmdir() function takes a single argument, which
is the path of the directory to be deleted.
#
Delete a file
os.remove("file.txt")
#
Delete an empty directory
os.rmdir("directory")
Note: The
rmdir() function can only delete empty directories. To delete a directory and
its contents, use the shutil module.
Copying files:
To copy a file in Python using the os
module, you can use the shutil module's copy() function. This function
takes two arguments: the path of the file to be copied, and the path of the
destination where the file will be copied to.
import
shutil
src_path
= "/path/to/source/file.txt"
dest_path
= "/path/to/destination/folder/"
shutil.copy(src_path,
dest_path)
Moving files:
To move a file in Python using the os
module, you can use the shutil module's move() function. This function
takes two arguments: the path of the file to be moved, and the path of the
destination where the file will be moved to.
import
shutil
src_path
= "/path/to/source/file.txt"
dest_path
= "/path/to/destination/folder/"
shutil.move(src_path,
dest_path)
datetime module
·
Python datetime module provides
classes and methods for working with dates and times.
·
This module provides a way to
represent, manipulate, and format dates, times, and time intervals in a Python
program.
Importing the datetime module:
We can import the datetime module using the
import statement:
import datetime
Working with dates:
·
A date in Python is represented
by the date class.
·
The date class has three
integer attributes: year, month, and day.
Example:
d =
datetime.date(2022, 3, 19)
print(d)
Output:
2022-03-19
We can also get the current date using the
today() method:
today
= datetime.date.today()
print(today)
Output:
2023-03-19
Working with times:
·
A time in Python is represented
by the time class.
·
The time class has five
attributes: hour, minute, second, microsecond, and tzinfo.
Example:
t =
datetime.time(12, 30, 45)
print(t)
Output:
12:30:45
We can also get the current time using the
now() method:
now
= datetime.datetime.now()
print(now)
Output:
2023-03-19
18:40:50.538280
Working with datetime:
·
A datetime in Python is represented
by the datetime class.
·
The datetime class has seven
attributes: year, month, day, hour, minute, second, and microsecond.
dt =
datetime.datetime(2023, 3, 19, 18, 30, 45)
print(dt)
Output:
2023-03-19
18:30:45
We can also get the current datetime using
the now() method:
now
= datetime.datetime.now()
print(now)
Output:
2023-03-19
18:40:50.538280
Formatting dates and times:
·
We can format dates and times
using the strftime() method.
·
The strftime() method takes a
format string as an argument and returns a formatted string.
now
= datetime.datetime.now()
print(now.strftime("%Y-%m-%d
%H:%M:%S"))
Output:
2023-03-19
18:40:50
Timedelta:
·
The timedelta class represents
a duration, the difference between two dates or times.
·
We can create a timedelta
object by subtracting two dates or times.
td =
datetime.timedelta(days=30, hours=12)
print(td)
Output:
30
days, 12:00:00
We can also add or subtract a timedelta
object from a date, time, or datetime object.
now
= datetime.datetime.now()
td =
datetime.timedelta(days=30, hours=12)
future
= now + td
print(future)
Output:
2023-04-18
06:40:50.538280
math Module
The
math module in Python is a built-in library that provides access to a set of
mathematical functions and constants.
It
is part of the standard library, so you don't need to install any additional
software to use it. The math module includes a wide range of functions, such as
trigonometric functions, logarithmic functions, and statistical functions. Here
are some of the most commonly used functions and constants in the math package:
Trigonometric
functions:
·
sin(x): returns the sine of x, where x is in radians
·
cos(x): returns the cosine of x, where x is in radians
·
tan(x): returns the tangent of x, where x is in radians
·
asin(x): returns the arcsine of x in radians
·
acos(x): returns the arccosine of x in radians
·
atan(x): returns the arctangent of x in radians
·
degrees(x): converts x from radians to degrees
·
radians(x): converts x from degrees to radians
Logarithmic
functions:
·
log(x): returns the natural logarithm of x (base e)
·
log10(x): returns the base-10 logarithm of x
·
exp(x): returns the value of e raised to the power of x
Statistical
functions:
·
min(x1, x2, ..., xn): returns the smallest value among the given
arguments
·
max(x1, x2, ..., xn): returns the largest value among the given
arguments
·
sum(iterable): returns the sum of all the values in the given iterable
·
mean(iterable): returns the arithmetic mean of the values in the given
iterable
·
median(iterable): returns the median value of the values in the given
iterable
Constants:
·
pi: the mathematical constant pi (3.141592...)
·
e: the mathematical constant e (2.718281...)
Comments
Post a Comment