Exploring Python’s OS Module
https://ift.tt/2WtHzrj
Python OS modules allow users to interact with files and directories. There are many functions or methods that Python employs in working with files or directories. However, in this article, we will consider three (3) essential functions. Now, let’s dive straight into it!
Python – os.rename()
Python OS rename()
file method renames a file or directory. This method works by passing two arguments named; src
(Source) and dst
(Destination).
Syntax:
os.rename(src, dst)
Parameters:
- Source: This is a path-like object which represents a file system path. It is the target source file path to be renamed.
- Destination: This is a path-like object which represents a file system path.
Return Type: The os.rename()
method does not return any value.
Code 1: How the os.rename()
function works
# These codes explain the os.rename() method
# how to import os module
import os
# Source file path
source = 'Finx/ster.txt'
# destination file path
dest = 'Finx/newster.txt'
# Using os.rename()method, rename the source path to destination path
os.rename(source, dest)
print("Source path successfully renamed to destination path.")
Output:
Source path successfully renamed to destination path
Code #2: How to treat likely errors
# These codes explain the os.rename() method
# how to import os module
import os
# Source file path
source = './Finx/ster.txt'
# destination file path
dest = './finx/dir'
# using os.rename()method, attempt renaming src path to dst path
try :
os.rename(source, dest)
print("Source path successfully renamed to destination path.")
# If Source is a file
# but destination is a directory
except IsADirectoryError:
print("Source is file, but destination is directory.")
# If source is a directory
# but destination is a file
except NotADirectoryError:
print("Source is directory, but destination is file.")
# For permission related errors
except PermissionError:
print("Operation not permitted.")
# For other errors
except OSError as error:
print(error)
Output:
Source is file, but destination is directory
Creating a directory in Python
Python OS Module uses a couple of methods to create a directory. They are :
Using os.mkdir()
Python uses the os.mkdir()
method to create a directory known as “path” with the specified numeric mode. If the directory that should be created already exists, os.mkdir()
returns FileExistsError
message in such situation.
Syntax:
os.mkdir()
and in optional cases the extension – “(path, mode = 0o777, *, dir_fd = None)“ – may be added to the syntax.
Parameter:
- Path: This is a path-like object which represents a file system path. This path-like object is either a string or bytes object.
- Mode (optional): This is an integer value which represents the mode of the directory to be created. If this parameter is missing, then the default value: Oo777 is applied.
- dir_fd (optional): This is a file descriptor referring to a directory. It’s important to note that the default value of this parameter is ‘None’. Please note that
dir_fd
is ignored, If the specified path is absolute. Please note that the ‘*’
in the parameter list indicates that all following parameters (in this case ‘dir_fd’
) are keyword-only.
Return Type: Please note that this method does not return any value
Example #1: How to create a file or directory using the os.mkdir()
method
# These codes explain os.mkdir()method
# importing os module
import os
# Directory
directory = "Finx"
# Parent Directory path
parent_dir = "D:/Pycharm projects/"
# Path
path = os.path.join(parent_dir, directory)
# Create the directory
# 'Finxter' in
# '/home / User / Documents'
os.mkdir(path)
print("Directory '% s' created" % directory)
# Directory
directory = "Finxter"
# Parent Directory path
parent_dir = "D:/Pycharm projects"
# mode
mode = 0o666
# Path
path = os.path.join(parent_dir, directory)
# Create the directory
# 'Finx' in
# '/home / User / Documents'
# with mode 0o666
os.mkdir(path, mode)
print("Directory '% s' created" % directory)
Output:
Directory 'Finx' created
Directory 'Finxter' created
Example #2: Likely errors while using the os.mkdir()
method.
# These codes explain os.mkdir() method
# importing os module
import os
# Directory
directory = "Finx"
# Parent Directory path
parent_dir = "D:/Pycharm projects/"
# Path
path = os.path.join(parent_dir, directory)
# Create the directory
# 'Finx' in
# '/home / User / Documents'
os.mkdir(path)
print("Directory '% s' created" % directory)
# if directory / file that
# is to be created already
# exists then 'FileExistsError' message
# will be returned by os.mkdir() method
# Similarly, if the specified path
# is invalid 'FileNotFoundError' Error
# will be flagged
Output:
Traceback (most recent call last):
File “gfg.py”, line 18, in
Os.mkdir(path)
FileExistsError: [WinError 183] Cannot create a file when that file /
/already exists: ‘D:/Pycharm projects/Finx’
Example #3: How to treat likely errors while using os.mkdir()
method.
# These codes explain os.mkdir()method
# importing os module
import os
# path
path = 'D:/Pycharm projects / Finx'
# Create the directory
# 'finx' in
# '/home / User / Documents'
try:
os.mkdir(path)
except OSError as error:
print(error)
How to Check if a File or Directory Exists
Python is a popular, general-purpose, and advanced programming language. It is known to have many functionalities, and one of such functionalities is the ability to check if a file or directory already exists or not. Python performs this task with the help of an in-built os module.
With the OS module, Python provides functions needed to interact with the operating system. OS falls under Python’s standard utility modules and those modules provide an efficient way of utilizing operating system dependent functionalities. The os.path
module is a submodule of the within Python, used to manipulate common path names.
How to check if a file exists already
The
os.path.isfile()
method checks whether the specified path is an existing file or not. Please note that os.path.isfile()
follows symlinks.
Syntax: os.path.isfile(path)
Parameter:
- Path: This is a path-like object which represents a file system path. This path-like object is either a string or bytes object.
Return Type: This method returns a Boolean value. it returns ‘True’
if the specified path is an existing file. Otherwise, it returns ‘False’
.
Example:
# These codes explain os.path.isfile() method
# importing os module
import os
# Path
path = 'D:/Pycharm projects/Finx/vos/quiz_vos.txt'
# Check whether the
# specified path is
# an existing file
isFile = os.path.isfile(path)
print(isFile)
# Path
path = 'D:/Pycharm projects/Finx/vos/'
# Check whether the
# specified path is
# an existing file
isFile = os.path.isfile(path)
print(isFile)
Output:
True
False
How to check if a directory exists
Python uses the os.path.isdir()
method to check whether a specified path is an existing directory or not. This method follows a symbolic link, which means if the specified path is a symbolic link pointing to a directory, then the process returns ‘True’
.
Syntax: os.path.isdir(path)
Parameter:
- Path: This is a path-like object which represents a file system path.
Return Type: This method returns a Boolean value. This method returns ‘True’
if the specified path is an existing directory. Otherwise, it returns ‘False’
.
Example #1: How to use the os.path.isdir()
method.
# These codes explain os.path.isdir() method
# importing os.path module
import os.path
# Path
path = 'D:/Pycharm projects/Finx/vos/quiz_vos.txt'
# Check whether the
# specified path is an
# existing directory or not
isdir = os.path.isdir(path)
print(isdir)
# Path
path = 'D:/Pycharm projects/Finx/vos/'
# Check whether the
# specified path is an
# existing directory or not
isdir = os.path.isdir(path)
print(isdir)
Output:
False
True
Example #2: What happens if the specified path is a symbolic link?
# These codes explain os.path.isdir() method.
# importing os.path module.
import os.path
# Create a directory(in current working directory).
dirname = "Finx"
os.mkdir(dirname)
# Create a symbolic link pointing to the above directory.
symlink_path = "D:/Pycharm projects/Finx/vos/"
os.symlink(dirname, symlink_path)
path = dirname
# Investigate if the specified path is an existing directory or not.
isdir = os.path.isdir(path)
print(isdir)
path = symlink_path
# Check whether the specified path - a symbolic link - is an
# existing directory or not.
isdir = os.path.isdir(path)
print(isdir)
Output:
True
True
How to check if either file or directory exists
Python uses the os.path.exists()
method to check whether a specified path exists or not. This method also checks if the given path refers to an open file descriptor or not. The method checks if either a file or directory exist.
Syntax: os.path.exists(path)
Parameter:
Path: This is a path-like object which represents a file system path. This path-like object is either a string or bytes object.
Return Type: This method returns a Boolean value. The
os.path.exists()
method returns ‘True’, if the path exists. Otherwise, it returns ‘False’.
Example:
# These codes explain os.path.exists() method
# importing os module
import os
# Path
path = 'D:/Pycharm projects/Finx/vos/quiz_vos.txt'
# Find out if the specified path is an existing file.
isExist = os.path.exists(path)
print(isExist)
# Path
path = 'D:/Pycharm projects/Finx/vos/'
# Finally, check if the specified path is an existing file.
isExist = os.path.exists(path)
print(isExist)
Output:
True
True
Please note that even if the path exists, the os.path.exists()
function may still return ‘False’, if the execution of os.stat()
is not authorized.
To learn more about Python, become a Finxter Scholar. Join here https://blog.finxter.com/email-academy/ now!
Reference
The post Exploring Python’s OS Module first appeared on Finxter.
Python
via Finxter https://ift.tt/2HRc2LV
December 20, 2020 at 09:29AM