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

13. Directories and Modules in Python

Uploaded by

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

13. Directories and Modules in Python

Uploaded by

KETKI SONAWANE
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 39

Directories and Modules in Python

Introduction
 A directory or folder is a collection of files and sub
directories.
 Python has the os module, which provides a big range of
useful methods to manipulate files and directories.
Get Current Directory
 We can get the present working directory using
the getcwd() method.
 This method returns the current working directory in the
form of a string.

import os
print(os.getcwd())
Changing Directory
 We can change the current working directory using
the chdir() method.
 The new path that we want to change to must be given as
a string to this method.
 We can use both forward slash (/) or the backward slash
(\) to separate path elements.
 It is safer to use escape sequence when using the
backward slash.

import os
os.chdir('C:\\Python33')
print(os.getcwd())
Making a New Directory
 We can make a new directory using the mkdir()
method.
 This method takes in the path of the new directory.
 If the full path is not specified, the new directory is
created in the current working directory.

import os
os.mkdir('test')
Renaming a Directory or a File
 The rename() method can rename a directory or a file.
 The first argument is the old name and the new name
must be supplies as the second argument.

import os
print(os.listdir())
os.rename('test','new_one')
print(os.listdir())
Removing Directory or File
 A directory can be removed using remove() method.
 However, we can remove an empty directory using
the rmdir() method.

import os
print(os.listdir())
os.rmdir('new_one')
print(os.listdir())
Time module
Introduction
 Python has a module named time to handle time-related
tasks.
 To use functions defined in the module, we need to
import the module first.
time( ) function
 The time() function returns the number of seconds passed
since epoch.
 The "epoch" serves as a reference point from which time is
measured.
 January 1, 1970, 00:00:00 is epoch.

import time
s = time.time()
print("Seconds since epoch =", s)

 Output:
Seconds since epoch = 1554114293.8340213
ctime( ) function
 The ctime() function takes seconds passed since epoch
as an argument and returns a string representing local
time.

import time
s = 1545925769.9618232 # seconds passed since epoch
t = time.ctime(s)
print("Local time:", t)

 Output:
Local time: Mon Apr 1 16:02:56 2019
sleep( ) function
 The sleep() function suspends (delays) execution of the
current thread for the given number of seconds.

import time
print("This is printed immediately.")
time.sleep(2.4)
print("This is printed after 2.4 seconds.")

Output:
This is printed immediately.
This is printed after 2.4 seconds.
time.struct_time Class
 Several functions in the time module such as gmtime(),
asctime() etc. either take time.struct_time object as
an argument or return it.
 Here's an example of time.struct_time object.
time.struct_time(tm_year=2018, tm_mon=12,
tm_mday=27, tm_hour=6, tm_min=35, tm_sec=17,
tm_wday=3, tm_yday=361, tm_isdst=0)
time.struct_time attributes
Index Attribute Values

0 tm_year 0000, ...., 2018, ..., 9999


1 tm_mon 1, 2, ..., 12
2 tm_mday 1, 2, ..., 31
3 tm_hour 0, 1, ..., 23
4 tm_min 0, 1, ..., 59
5 tm_sec 0, 1, ..., 61
6 tm_wday 0, 1, ..., 6; Monday is 0
7 tm_yday 1, 2, ..., 366
8 tm_isdst 0, 1 or -1
Some more function in time module
Function Description
time.localtime() Takes the number of seconds passed since epoch as an
argument and returns struct_time in local time.
time.gmtime() Takes the number of seconds passed since epoch as an
argument and returns struct_time in UTC.
time.mktime() Takes struct_time (or a tuple containing 9 elements
corresponding to struct_time) as an argument and
returns the seconds passed since epoch in local time.
time.asctime() Takes struct_time (or a tuple containing 9 elements
corresponding to struct_time) as an argument and
returns a string representing it.
time.strftime() Takes struct_time (or tuple corresponding to it) as an
argument and returns a string representing it based on
the format code used.
time.strptime() Parses a string representing time and
returns struct_time.
time.localtime()
 The localtime() function takes the number of seconds passed since epoch
as an argument and returns struct_time in local time.

import time
result = time.localtime(1545925769)
print("result:", result)
print("\nyear:", result.tm_year)
print("tm_hour:", result.tm_hour)

 Output:
result: time.struct_time(tm_year=2018, tm_mon=12, tm_mday=27,
tm_hour=21, tm_min=19, tm_sec=29, tm_wday=3, tm_yday=361,
tm_isdst=0)

year: 2018
tm_hour: 21
datetime module
datetime module
 Python has a module named datetime to work with
dates and times.
 Commonly used classes in the datetime module are:
1. date Class
2. time Class
3. datetime Class
4. timedelta Class
Get Current Date
import datetime
x = datetime.date.today()
print(x)

 Output:
2019-04-03

 In this program we have imported datetime module


using import datetime statement.
 One of the classes defined in the datetime module
is date class.
 We have used today() method defined in the date class to get
a dateobject containing the current local date.
Get Current Date and Time
import datetime
x = datetime.datetime.now()
print(x)

 Output:
2019-04-03 10:26:36.260012

 In this program we have used now() method from


datetime class to create a datetime object containing the
current local date and time.
Importing only specific class
 We can only import date class from the datetime
module.
from datetime import date
a = date(2019, 4, 3)
print(a)

 Get current date:


from datetime import date
a = date.today()
print("Current date =", a)
Continued…..
 Print today's year, month and day -
 We can get year, month, day etc. from the date object
easily.

from datetime import date


a = date.today()
print("Current year:", a.year)
print("Current month:", a.month)
print("Current day:", a.day)
Continued…..
 We can only import time class from the datetime
module.

from datetime import time


a = time() # time(hour = 0, minute = 0, second = 0)
print("a =", a)
b = time(11, 34, 56)
print("b =", b)
Continued…..
 The datetime module has a class named datetime that
can contain information from both date and time
objects.

from datetime import datetime


a = datetime(2018, 11, 28)
print(a)
# datetime(year, month, day, hour, minute, second,
microsecond)
b = datetime(2019, 4, 3, 23, 55, 59, 342380)
print(b)
Continued…..
 A timedelta object represents the difference between two
dates or times.

from datetime import datetime, date


t1 = datetime(year = 2018, month = 7, day = 12, hour = 7,
minute = 9, second = 33)
t2 = datetime(year = 2019, month = 6, day = 10, hour = 5,
minute = 55, second = 13)
t3 = t1 - t2
print("t3 =", t3)

 Output:
t3 = -333 days, 1:14:20
Difference between two timedelta objects
from datetime import timedelta
t1 = timedelta(weeks = 2, days = 5, hours = 1, seconds =
33)
t2 = timedelta(days = 4, hours = 11, minutes = 4, seconds =
54)
t3 = t1 - t2
print("t3 =", t3)

 Output:
t3 = 14 days, 13:55:39
Get date from a timestamp
 We can also create date objects from a timestamp.
 A timestamp is the number of seconds between a particular
date and January 1, 1970 at UTC.
 UTC (Coordinated Universal Time) is the primary time
standard by which the world regulates clocks and time.
 You can convert a timestamp to date using fromtimestamp()
method.

from datetime import date


ts = date.fromtimestamp(1554272155.8145545)
print("Date =", ts)

Output:
Date = 2019-04-03
Python format datetime
 The date and time can be represented in different ways at
different places, organizations etc.
 It's more common to use mm/dd/yyyy in the US,
whereas dd/mm/yyyy is more common in the UK.
 Python has strftime() and strptime() methods to handle
this.
1. Python strftime() - datetime object to
string
 The strftime() method is defined under classes date, datetime and time.
 The method creates a formatted string from a given date, datetime or time object.

from datetime import datetime


n = datetime.now() # returns current date and time
t = n.strftime("%H:%M:%S")
print("time:", t)
s1 = n.strftime("%m/%d/%Y, %H:%M:%S") # mm/dd/YY H:M:S format
print("s1:", s1)
s2 = n.strftime("%d/%m/%Y, %H:%M:%S") # dd/mm/YY H:M:S format
print("s2:", s2)

 Output:
time: 10:42:57
s1: 04/03/2019, 10:42:57
s2: 03/04/2019, 10:42:57
Continued…..
 Here, %Y, %m, %d, %H etc. are format codes.
 The strftime() method takes one or more format codes
and returns a formatted string based on it.
Format Range
%Y year [0001,..., 2018, 2019,..., 9999]
%m month [01, 02, ..., 11, 12]
%d day [01, 02, ..., 30, 31]
%H hour [00, 01, ..., 22, 23
%M minutes [00, 01, ..., 58, 59]
%S second [00, 01, ..., 58, 59]
2. Python strptime() - string to datetime
 The strptime() method creates a datetime object from a given
string (representing date and time).

from datetime import datetime


date_string = "21 June, 2018"
print("date_string =", date_string)
date_object = datetime.strptime(date_string, "%d %B, %Y")
print("date_object =", date_object)

 Output:
date_string = 21 June, 2018
date_object = 2018-06-21 00:00:00
Continued…..
 The strptime() method takes two arguments:
1. a string representing date and time
2. format code equivalent to the first argument
 By the way, %d, %B and %Y format codes are used
for day, month(full name) and year respectively.
Calendar Module
Introduction
 Python defines an inbuilt module calendar which handles
operations related to calendar.
 Calendar module allows output calendars like the
program and provides additional useful functions related
to the calendar.
 By default, these calendars have Monday as the first day of
the week, and Sunday as the last (the European
convention).
Display Calendar of given month
import calendar
yy = 2019
mm = 4
print(calendar.month(yy, mm))
Display calendar of given year.
 Syntax: calendar(year, w, l, c)
1. year: Display year,
2. w:width of characters,
3. l: no. of lines per week
4. c: column separations.

import calendar
print ("The calender of year 2019 is : ")
print (calendar.calendar(2019, 2, 1, 6))
class calendar.Calendar :
 Calendar class creates a Calendar object.
 A Calendar object provides several methods that can be
used for preparing the calendar data for formatting.
 This class doesn’t do any formatting itself.
 Calendar class allows the calculations for various task
based on date, month, and year.
Calendar class methods
FUNCTION DESCRIPTION
Returns an iterator for the week day numbers that will be
iterweekdays()
used for one week
itermonthdates() Returns an iterator for the month (1–12) in the year
itermonthdays() Returns an iterator of a specified month and a year
Method is used to get an iterator for the month in the year
similar to itermonthdates(). Days returned will be tuples
itermonthdays2()
consisting of a day of the month number and a week day
number.
Returns an iterator for the month in the year similar to
itermonthdates(), but not restricted by the datetime.date
itermonthdays3()
range. Days returned will be tuples consisting of a year, a
month and a day of the month numbers.
Used to get a list of the weeks in the month of the year as full
monthdayscalendar
weeks
iterweekdays()
 This method returns an iterator for the week day
numbers that will be used for one week.
 The first number from the iterator will be the same as
the number returned by firstweekday().

import calendar
# providing firstweekday = 0
obj = calendar.Calendar(firstweekday = 0)
for day in obj.iterweekdays():
print(day)

You might also like