Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
3 views

Python Unit 5

Chapter 5 of the Python Programming Unit-5 Notes covers Python's standard libraries for file handling, including the pathlib module for working with paths and directories. It explains how to create, read, write, and manipulate files, as well as how to work with CSV files and handle date and time using the time and datetime modules. The chapter provides examples of methods for checking file existence, renaming, deleting files, and converting between string and datetime formats.

Uploaded by

Owais Khan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Python Unit 5

Chapter 5 of the Python Programming Unit-5 Notes covers Python's standard libraries for file handling, including the pathlib module for working with paths and directories. It explains how to create, read, write, and manipulate files, as well as how to work with CSV files and handle date and time using the time and datetime modules. The chapter provides examples of methods for checking file existence, renaming, deleting files, and converting between string and datetime formats.

Uploaded by

Owais Khan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

Python Programming Unit-5 Notes

CHAPTER 5 - Python Standard Libraries

Working with path, files and directories


Python supports file handling and allows users to handle files i.e., to read and write files,
along with many other file handling options, to operate on files. Python treats file differently as text
or binary and this is important. Each line of code includes a sequence of characters and they form
text file. Each line of a file is terminated with a special character, called the EOL or End of Line
characters like comma {,} or newline character. It ends the current line and tells the interpreter a new
one has begun.

Working with paths

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.

We can import the Path class from pathlib module as below:

from pathlib import Path

We can create a path class object like:

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( )

Let us create a path object to get the use of some methods.

path = Path(“D://testmodule/test.txt”)

We can check if the path exists or not by exists method.

path.exists()
We can also check if the path represents a file or not.

path.is_file()
Python Programming Unit-5 Notes

Same thing we can check for directory.

path.is_dir()

We can get the file name in the path by name property.

print(path.name)

We can get the file name without extension by stem property.

print(path.stem)

Same way, we can get the extension only by suffix property.

print(path.suffix)

will display .py

We can get the parent directory by using parent property.

print(path.parent)

We can also display the absolute path by using absolute method.

print(path.absolute())

Working with Directories

As we have already covered, Path object can be created using:

path = Path(“test”)

We can create and remove directories as follows.

path.mkdir(‘name’)

path.rmdir(‘name’)

Also, we can rename it by:

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.

Working with Files

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”)

We can check if the file exists or not using:

path.exists()

We can rename the file using rename method.

path.rename(“init.txt”)

We can delete the file using unlink method.

path.unlink()

We can check the details of the file using stat method.

print(path.stat())

Reading from a file can be done using read_text method.

print(path.read_text())

Similarly, we can write into the file using write_text method.

path.write_text(“Hello All”)
Python Programming Unit-5 Notes

Working with CSV

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.

We can use csv module to work with csv files.

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)

As mentioned, we need to pass file object to this method.

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)

for row in reader:

print(row)
Python Programming Unit-5 Notes

Working with time and datetime

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.

Let us see first how we can use time module.

import time

time1 = time.time()

curr = time.ctime(time1)

print(“current time”,curr)

Output:

Wed Nov 23 14:40:52 2022

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.

from datetime import datetime

Now, we can create a datetime object by mentioning year, month and day. Optionally we can
mention hour, minutes and seconds too.

dt = datetime(2022, 12, 25)

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)

print(dt2 > dt1)

Above code will print TRUE as date in dt2 is greater.

You might also like