Library os

by Alex
Library os
The os module of the Python standard programming language library is normally used to manipulate the installed operating system as well as the PC file system. It contains many useful methods for interacting with files and folders on your hard disk. Programs that work with the os module are OS-independent and are easily portable to another platform.

What is an os module?

The os module in Python is a library of functions for working with the operating system. The methods it contains allow you to define the type of operating system, access environment variables, and manage directories and files:

  • check the existence of the object along the given path;
  • determining the size in bytes;
  • deletion;
  • renaming, etc.

When calling os functions it is important to keep in mind that some of them may not be supported by the current OS.

To use methods from os, you need to include a library. Python uses import os to do this, which must be described in the file before calling the module for the first time.

It is recommended to use this instruction at the beginning of the source code file.

The functions of the os module

Methods from the os library can be used by the user for different purposes. The most popular ones are listed below to get information about the operating system. It can also gather information about the files and folders stored on your computer’s hard drive.

Getting information about your operating system

To find out the name of the current operating system, it is enough to use the name method. Depending on the platform installed, it will return its short name in string representation. The following program was run on a Windows 10 PC, so the result of the name function is the string nt. You can see this using the normal print method.

import os
print(os.name)

nt

To get the information that relates to the computer’s configuration, the environ method can be used. Calling it by calling the os library, the user gets a big dictionary with environment variables, which is output to the console or a string variable. In this way, the system disk name, home directory address, system name, and a lot of other information can be found. The following example demonstrates the use of environ.

import os
print(os.environ)

environ({'ALLUSERSPROFILE': 'C:ProgramData', ...})

The getenv function can be used to access various environment variables. To do that, just pass in the name of the variable as an argument, as in the following example, where print brings up the TMP information on the display in the console.

import os
print(os.getenv("TMP"))

C:UsersadminAppDataLocalTemp

Change working directory

By default, the working directory of the program is the directory that contains its source document. That way you don’t have to specify an absolute path to the file if it is located in this directory. To get information about the current directory, the function getcwd returns the full address of the working directory on your hard disk. The following code snippet shows what will happen if you pass the result of this method to print. As you can see the working directory is the program directory on the C system disk.

import os
print(os.getcwd())

C:Usersadminsourcereposprogram

If you want, you can customize the working directory by using the chdir method of the os library. To do this you have to pass to it the absolute address of the new directory as a parameter. If the specified path does not actually exist, the program will crash because an exception was thrown. The following code example shows the transition to the new working directory called folder on the D drive.

import os
os.chdir(r "D:folder")

D:folder

Checking the existence of the path

To avoid mistakes caused by the absence of a certain file or directory to be handled by the program, you should first check for their existence using the exist method. By passing the path to the desired file or folder as an argument, you can expect a concise boolean true/false answer, telling you if the stated object exists or not in the computer memory. In the next example it tests the text file test.txt from the root directory D and returns True.

import os
print(os.path.exists("D:/test.txt"))

True

If an object on disk actually exists, it does not always mean that it has the right form for further processing. To check if a certain object is a file, the isfile function takes its address. You can see how it works in the following example where print shows the value True for the file test.txt.

import os
print(os.path.isfile("D:/test.txt"))

True

We could do the same to check if the object belongs to the class of directories by calling the isdir method of the os library for its address. As you can see, print print print will print False, because test.txt is not a directory.

import os
print(os.path.isdir("D:/test.txt"))

False

Creating directories

The capabilities of the os module allow not only to display information about already existing objects in memory but also to generate entirely new ones. For example, using the mkdir method, it is fairly easy to create a folder by simply specifying the desired path for it. In the following example, a new folder called folder is generated in the root directory of drive D using mkdir.

import os
os.mkdir(r "D:folder")

But this is not the end of the directory generation possibilities. With the makedirs function you can create as many new directories as you want, as long as the previous directory is the parent of the next one. So, the following example shows how to generate a whole chain of folders, consisting of folder, first, second and third.

import os
os.makedirs(r "D:folderfirstsecondthird")

Delete files and directories

You can get rid of a file you don’t need any more with the remove method and give it as an argument an absolute or relative path to the object. The short code below shows the removal of the document test.txt from the root directory of hard drive D on a PC.

import os
os.remove(r "D:test.txt")

To erase a folder from memory, you should use the built-in rmdir function and give it the address of the object. There are, however, some subtleties here, because the program will not allow you to freely delete a directory where other objects are stored. In that case, an error will be shown on the screen and an exception will be thrown. The following example uses the rmdir method to remove the empty folder directory.

import os
os.rmdir(r "D:folder")

To quickly remove multiple empty folders, you should call the removedirs function. It provides a way to get rid of several directories on disk at once, as long as they are all nested inside each other. Thus, by specifying the path to the final folder, you can easily remove all parent directories, but only if they end up being empty. This example shows the instant removal of four different folders: folder, first, second, third.

import os
os.removedirs(r "D:folderfirstsecondthird")

Runtime

The built-in functions of the os library let you run individual files and folders directly from the program. The startfile method, to which you should pass the address of the necessary object, perfectly copes with this task. The software used to open the document is determined automatically by the environment. For example, if you start an ordinary test.txt file, as in the following example, the standard notepad will be used. If you pass a directory link to the function, it will be opened with the built-in file manager.

import os
os.startfile(r "D:test.txt")

Get filename and directory name

Sometimes to interact with a document, you need to get its full name, including the resolution, but not the absolute path to it on disk. The function basename, which is contained in the path submodule of the os library, lets you convert an object address into a name. Thus, the following example shows the conversion of the test.txt path into a simple filename.

import os
print(os.path.basename("D:/test.txt"))

test.txt

The opposite situation arises when the user only needs to get the path to the file, without the object name itself. The method dirname, which returns the path to a given document as a string representation, helps to do this, as demonstrated in the short example below. Here print displays the address of a text document in the folder folder.

import os
print(os.path.dirname("D:/folder/test.txt"))

D:/folder

Calculating size

To find out the size of a document or a folder, you can use the getsize function, as in the following example for the file test.txt. The function prints the size of a given document in bytes. You can also use getsize to measure the size of directories.

import os
print(os.path.getsize("D:test.txt"))

136226

Renaming

The os library lets you quickly rename any file or directory using the rename method. This function takes two different arguments at once. The first is responsible for the path to the old document name, while the second is responsible for its new name. The example shows renaming a folder into catalog. Keep in mind that this method may generate an exception if no file exists in the given path.

import os
os.rename(r "D:folder", r "D:catalog")

You can rename not only one directory, but several folders at once, as long as they are all in the same hierarchical chain. To do that, just call the renames method and pass to it the path to the target directory as the first argument. The second argument is a similar folder address, but with new names for the whole chain. The next example shows the correct way to use the renames function, which rename the directories folder, first and second into catalog, one and two.

import os
os.renames(r "D:folderfirstsecond", r "D:catalogonetwo")

Contents of directories

The listdir function allows you to check if some objects are present in the directory. With its help, you can get information about files and folders in the form of a list. The program below shows how the method takes as its parameter the path to folder on the D drive and then prints the names of the internal folder first and the document test.txt to the console.

import os
print(os.listdir(r "D:folder"))

['first', 'test.txt']

Using the walk method, you can access the names and paths of all subfolders and files belonging to a given directory. Using one external for loop and two nested ones, it is easy to get information about the objects in the folder through special directories and files lists. The information is given by calling print multiple times.

import os
for root, directories, files in os.walk(r "D:folder"):
    print(root)
    for directory in directories:
        print(directory)
    for file in files:
        print(file)

D:folder
first
D:folderfirst
second
D:folderfirstsecond
third
D:folderfirstsecondthird
test.txt

Information about files and directories

You can display basic information about an object on the screen or anywhere else using the stat method. By giving it as a parameter the location of a file or folder on your computer, you should expect a small amount of information. Here you will find information about the size of the object in bytes and some numerical values to indicate access and mode.

import os
print(os.stat(r "D:test.txt"))

os.stat_result(st_mode=33206, ...)

Path handling

Returning to the path class from the os library, it is worth considering the split function, which makes it very easy to split the file path and file name into different strings. This is demonstrated by the following example with the text document test.txt in the folder.

import os
print(os.path.split(r "D:foldertest.txt"))

('D:folder', 'test.txt')

The join function does the reverse, making it easy to merge the path to the document with its name. As you can see from the results of this code, print will display the path that refers to the text file test.txt in the folder directory of D.

import os
print(os.path.join(r "D:folder", "test.txt"))

D:foldertest.txt

These were the basic features of the os module, implemented in Python programs through a variety of built-in methods to control the installed OS. Thus, they allow you not only to get useful information about the platform, but also to manipulate the contents of the disk by creating new directories and files, renaming and deleting them completely.

Related Posts

LEAVE A COMMENT