Download as pdf or txt
Download as pdf or txt
You are on page 1of 12

OS Module

OS Module
• The OS module in Python provides functions for interacting with the
operating system.
• To use the functionality available in OS module we have to import it
by writing the following code:
import os

3
Renaming file
• The rename() method takes two arguments, the current filename and
the new filename.
os.rename(“current_file_name”, “new_file_name”)

4
Deleting file
• The remove() method to delete files by supplying the name of the file to
be deleted as the argument.
os.remove(“file_name”)

5
Make Directories
• The mkdir() method is used to create directories in the current
directory. You need to supply an argument to this method which
contains the name of the directory to be created.
os.mkdir(“new dir”)

6
Change Directories
• The chdir() method to change the current directory. The chdir()
method takes an argument, which is the name of the directory that
you want to make the current directory.
os.chdir(“new dir”)

7
Current working directory
• The getcwd() method displays the current working directory.
os.getcwd()

8
Delete directory
• The rmdir() method deletes the directory, which is passed as an
argument in the method.
os.rmdir(‘dir name’)

9
Listing Files and Directory
• The listdir() method is used to get the list of all files and directories in
the specified directory.
• If we don’t specify any directory, then list of files and directories in
the current working directory will be returned.
dir_list = os.listdir(path)

10
File Information (Metadata)
• By giving the path of the file, we can get more information about the
file.
• os.path.getsize() returns the size of the file
• os.path.getmtime() returns the file last modified date
• os.path.getctime() returns the file creation date
• os.stat() returns all the information you need in a concise way

11
File Information (Metadata)
import os
filename=“C:\\Users\\shamik.tiwari\\Desktop\\share.txt”
os.path.getsize(filename)
os.path.getmtime(filename) #get the time of last modification of the specified path
os.path.getctime(filename) #creation time
os.stat(filename) #This method is used to get status of the specified path

12

You might also like