Python Notes ch5
Python Notes ch5
Path class is a basic building block to work with files and directories.
Path(“C:\\Program Files\Microsoft”)
We can also create a Path object that represents a current directory like:
Path()
We can also get the home directory of current user using home method.
Path.home( )
path = Path(“ecommerce/__init__.py”)
path.exists()
path.is_file()
path.is_dir()
print(path.name)
print(path.stem)
print(path.suffix)
print(path.parent)
print(path.absolute())
We can create a new path from existing path using with_name method.
path = Path(“ecommerce”)
path.mkdir()
path.rmdir()
path.rename(“ecommerce2”)
Python Programming Unit-5 Notes
Now, to iterate through all the files and directories we can use the following code.
for p in path.iterdir():
print(p)
Above code shows all the directories and files on the mentioned path. So, if we want to see just the
directories, we can use:
print(p)
This method has two limitations. It can not search by patterns and it can not search recursively. So, to
overcome this limitation, we can use glob method.
To search for patterns, say to search for all python files, we can use glob method as below.
for p in path.glob(“*.py”)
print(p)
for p in path.glob(“**/*.py”)
print(p)
for p in path.rglob(“*.py”)
print(p)
To see how we can work with files, let us refer to the file we want to work with using Path class object.
path = Path(“ecommerce/__init.py__”)
path.exists()
path.rename(“init.txt”)
Python Programming Unit-5 Notes
path.unlink()
print(path.stat())
print(path.read_text())
path.write_text(“Hello All”)
Let us take the new path which refers to the _init__.py file in current directory.
Now we can copy the file contained in path on above target by writing:
target.write_text(path.read_text())
There is a better way to do this. We can use a module shutil stands for shell utility to perform this.
import shutil
shutil.copy(path,target)
CSV stands for Comma Separated Values which is a file that stores the values separated with comma.
They serve as simple means to store and transfer data.
import csv
We can open a csv file and write into it by using built in open function.
file = open(“data.csv”,”w”)
Python Programming Unit-5 Notes
Now, this csv module has writer method to write content into csv file.
writer = csv.writer(file)
Now, we can use writer to write tabular data into csv file. For this, we need to use writerow method to
which we need to pass values in form of array.
write.writerow([“transaction_id”,”product_id”,”price”])
write.writerow([1000,1,5])
write.writerow([1001,2,15])
file.close()
Here, we have created three rows with three columns in a csv file.
Now, we can read the csv file using reader method. First, we need to open the file in read mode. For
that we do not require to pass the mode in second parameter. After opening the file, we can use reader
method to read the file. Once file has been read, we convert it into list using list method. And then we
can iterate through that list to read the content of csv file.
file = open(“data.csv”)
reader = csv.reader(file)
list(reader)
print(row)
There are two modules which we can use to work with date and time. time and datetime. time refers to
the current timestamp, which represents the number of seconds passed after the time started, which is
usually 1stJanuary, 1970.
import time
print(time.time())
Python Programming Unit-5 Notes
This statement will print the number of seconds passed after the date and time mentioned above.
This method can be used to perform time calculations such as duration to perform some task.
To work with date and time, we can use datetime class of datetime module.
Now, we can create a datetime object by mentioning year, month and day. Optionally we can mention
hour, minutes and seconds too.
We can also create a datetime object which represents the current date and time.
dt = datetime.now()
While taking input from user or reading from s file we deal with strings. So, when we read date or time
from such sources, we need to convert this input to datetime object. We can use strptime method for
this purpose.
Let us assume that we received a date 2022/12/25 as a string input. To convert it to datetime object,
we need to specify which part of full date represents what. So, we can do that by writing:
dt = datetime.strptime(“2022/12/25”, “%Y/%m/%d”)
Where, %Y, %m and %d are directives to represent four-digit year, two-digit month and two-digit date
respectively.
We can use strftime method to do excat opposite, i.e. convert datetime object to string.
dt = datetime(2022,12,25)
print(dt.strftime(“%Y/%m/%d”))
Similarly, we can convert timestamp into datetime object using fromtimestamp() method.
import time
dt = datetime.fromtimestamp(time.time())
datetime object has properties like year and month which we can use to print year and month.
print(dt.year)
print(dt.month)
Python Programming Unit-5 Notes
We can also compare two datetime objects to know which date is greater.
dt1 = datetime(2022,1,1)
dt2 = datetime(2022,12,25)
Sending Emails
For sending emails in python, we need to form an email and connect to the SMTP server.
To form an email, we need to import a package called multipart which is a sub package of mime
package, which is again sub package of email package. MIME stands for Multipurpose Internet Mail
Extension, which is a standard that defines the format for email messages.
message = MIMEMultipart()
message[“from”] = “SenderUser”
message[“to”] = [email protected]
mime does not support the header called ‘body’. So, we need to attach the body. For this, we need to
import MIMEText class from text module and then we can use this with ‘attach’ method of
MIMEMultipart object. To import the module, we need to write the following line on the top.
messege.attach(MIMEText(“Body”))
If we want to send an email with html, we can set second parameter as “html”.
We have now prepared out email. Now, we need to send this email through SMTP server.
For that we write following code and then see each line of code into it.
import smtplib
Python Programming Unit-5 Notes
smtp.ehlo()
smtp.starttls()
smtp.login(“[email protected]”,”test123”)
smtp.send_message(message)
smtp.close()
First of all, we need to import the smtplib module. In this module, there is a class SMTP. We pass two
keyword arguments to this class namely host and port. These two parameters depend upon the server
we are using. Next, we need to use few methods using SMTP object. First, we use method ehlo. This
is a part of SMTP protocol to start the process of sending an email. Next, we call starttls method which
puts SMTP into TLS mode. TLS stands for Transport Layer Security which is required for encryption
of commands. Now, we can login using email id and password using login method. And finally, we
can send a message using send_message method.