2

Python : OS Module

 2 years ago
source link: https://dev.to/anjalikumawat2002/python-os-module-ccb
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

The os module is a part of the standard library, or stdlib, within Python 3.

Python os module provides methods that help us to perform file processing operations. Let’s explore these basic functions one by one.

Using os

Before you use the os module, you first need to bring it up by means of the Python import command:

import os
Enter fullscreen modeExit fullscreen mode

If you try to run os without importing it, you will see an error message:

NameError: name 'os' is not defined
Enter fullscreen modeExit fullscreen mode

To get a list of functions supported by os module, run the below command:

print(dir(os))
Enter fullscreen modeExit fullscreen mode

Files

Some of the methoods of the os module to work with files.

rename() method :

It is used to rename a file or directory.

os.rename(old_filename,new_filename)
Enter fullscreen modeExit fullscreen mode

Example

os.rename(“file.txt”, “user.txt”)
Enter fullscreen modeExit fullscreen mode

remove() method :

It is used to delete the file.
Path : This is a path-like object which represents a file system path. This path-like object is either a string or bytes object.

os.remove(path_of_file)
Enter fullscreen modeExit fullscreen mode

Example

os.remove(“d1/user.txt”)
Enter fullscreen modeExit fullscreen mode

Directories

CWD == "Current working directory"

getcwd() method :

returns current directory.
or
To check the path of the current working directory, we will use the getcwd method.

print(os.getcwd())
Enter fullscreen modeExit fullscreen mode

Note The folder where the Python script is running is known as the Current Directory. This is not the path where the Python script is located.

mkdir() method :

It is used to create a directory in current directory.

os.mkdir("d1")
Enter fullscreen modeExit fullscreen mode

This method raises FileExistsError if the directory to be created already exists.

chdir() method :

Suppose, we have a folder, for example, info, inside our current directory, we can switch to the info folder, using the chdir function. or It is used to change the current directory.

os.chdir("info")
Enter fullscreen modeExit fullscreen mode

rmdir() method :

It is used to delete a directory. The directory must be empty before it is deleted.

os.rmdir("dirname")
Enter fullscreen modeExit fullscreen mode

listdir() method :

Returns a list containing names of files and subdirectories in the specified directory.

print(os.listdir())
Enter fullscreen modeExit fullscreen mode

Keep Learning!!
Keep Coding....❤️👩‍💻


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK