Automating tasks in Python: File and folder operations using the os module

In this new series of tutorials we will teach you how to automate tasks using the Python programming language, that can be useful when carrying out activities such as creating documents, or order them, writing programs with few lines of code in Python that can do this automatically. We will start by knowing how to interact with the files and folders of the operating system using the os module.

Variables are a good option for storing data while a program is running, giving a high and fast simplicity. But there may be times when it is necessary to store information of a type persistently and without having to resort to databases or other types of information storage.

For this case we can create files to store data, and in Python we can do it in a fast way and as is common, with few lines of code.

Note

In these examples the directories are used as in the windows and linux environment, review and adapt them to your operating system.

Files and Directories

A file has 2 main properties: a file name and a directory. The directory specifies the location of the file on the computer, for example, if the computer is on a computer with windows operating system, and the file name is program.exe, the path or directory of the file would be C:\users user documents.

Continuing, the folders in a directory, can contain files or other folders, as an example the following image:

In windows, backslashes are used to separate the paths or directories (\) as a separator between folder names. In OS X and linux we occupy the forward slash (/) to separate.

The module

In python we have the os module, which offers us all the tools to interact with the operating system, What: create folders, create or open files, folder lists, etc. This module is already included in the Python language, so no need to install it.

In all the examples the os module is used, therefore it must always be imported, this is done as follows:

Get current directory

Sometimes it is necessary to obtain the directory in which we are, this could be for a case, for example, in which we have to consume files as images.

To obtain the current directory we use the os module.

‘C:\\Python34’

Change directories

To change directory in python using the os module, we use the "chdir" method to which we pass the path we want to change to.

‘C:\\Windows\System32’

Absolute paths and relative paths

An absolute path is one that comes from the root folder.

A relative path is one that originates from the folder where the program runs, that is, the current route.

Create folders

With the module it is possible to create folders, this with the method "makedirs()”, for example:

Base name and directory

In specific cases it is necessary to split a file path, in the path and file name, we can do it using the "basename" and "dirname" methods

‘Calc.exe’

‘C:\\Windows\System32’

If you need to split the path into your folders and file, do the following:

(‘C:\\Windows\System32’, ‘Calc.exe’)

Delete folders

To delete a folder is done in a similar way:

File and folder size

Using the module it is possible to obtain the weight or size of the folders or files in general, it is done by calling the "os.path.getsize" method, in this way:

776192

Know if a route is valid or not

Know if a route is correct or not, it can save us a lot of headaches, for example if we ask the user to upload a document, it is necessary to verify if the path that the document gives us exists or not. Using the module we can do it in the following way:

  • True
  • False
  • True
  • False
  • False
  • True

Open files

To open a file in python use the "open" function, where the path indicated for the file to open is passed as text, this can be an absolute or relative path. The open function returns an object of type File.

To practice, create on your computer a file called "data.txt" and enter text data in the, run the following code to open it from python:

if you use linux or mac os, is:

Remember to replace the path in the example with the correct path from your system.

Read content from files

To read the content of the files that we have previously read, we use the "read" method, it is done as follows:

When executing this example we will read the information of the file and we will print its content on the screen.

IF the file contains text that is in many lines, we can read them using "readlines":

Writing files

Writing files is in a similar way, first we pass a file path to the open function, if the file we want to write does not exist, it will automatically be created to write information in the, It is important to emphasize that one more value will be passed to the open function, in this case it is the premise to write information. The example is as follows:

Other functions of the os module, are the following:

DescriptionMethod
Know if a file or directory is accessibleos.access(path, modo_de_acceso)
Know the current directoryos.getcwd()
Change working directoryos.chdir(nuevo_path)
Change to the root working directoryos.chroot()
Change the permissions of a file or directoryos.chmod(path, permisos)
Change the owner of a file or directoryos.chown(path, permisos)
Create a directoryos.mkdir(path[, modo])
Create directories recursivelyos.mkdirs(path[, modo])
Delete a fileos.remove(path)
Delete a directoryos.rmdir(path)
Delete directories recursivelyos.removedirs(path)
Rename a fileos.rename(actual, nuevo)
Create a symbolic linkos.symlink(path, nombre_destino)

Leave a Reply

Your email address will not be published. Required fields are marked *

one × three =