Python Unit 5
Python Unit 5
Pathlib module in Python provides various classes representing file system paths with semantics
appropriate for different operating systems. This module comes under Python’s standard utility
modules.
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(“D://testmodule/test.txt”)
path.exists()
We can also check if the path represents a file or not.
path.is_file()
Python Programming Unit-5 Notes
path.is_dir()
print(path.name)
print(path.stem)
print(path.suffix)
print(path.parent)
print(path.absolute())
path = Path(“test”)
path.mkdir(‘name’)
path.rmdir(‘name’)
path.rename(“abc”)
Now, to iterate through all the files and directories we can use the following code.
for p in path.iterdir():
print(p)
Python Programming Unit-5 Notes
Above code shows all the directories and files on the mentioned path. So, if we want to see just the
directories, we can use:
for p in path.iterdir():
if p.is_dir():
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 see how we can work with files, let us refer to the file we want to work with using Path class
object.
path = Path(“D://testmodule/test.txt”)
path.exists()
path.rename(“init.txt”)
path.unlink()
print(path.stat())
print(path.read_text())
path.write_text(“Hello All”)
Python Programming Unit-5 Notes
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”)
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)
reader = list(reader)
print(row)
Python Programming Unit-5 Notes
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
time1 = time.time()
curr = time.ctime(time1)
print(“current time”,curr)
Output:
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.
print(dt)
Output:
2022-12-25 00:00:00
We can also create a datetime object which represents the current date and time.
dt = datetime.now()
print(dt)
Output:
2022-11-23 09:32:02.429447
Python Programming Unit-5 Notes
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")
print(dt)
Output:
2022-12-25 00:00:00
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"))
Output:
2022/12/25
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)
Output:
2022
11
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)