13. Directories and Modules in Python
13. 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
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
Output:
2019-04-03 10:26:36.260012
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.
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.
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).
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)