9 minutes read

Sometimes, you may need to interact with the current operating system and access its features when working on your programs. You may need to know whether it would be easy to run it on other systems. If you need to get the list of files and folders in the current working directory, you may know that there are different commands for this on Linux/macOS and Windows.

It is useful to have the tools that would work on any OS so that you wouldn't need to handle all possible outcomes manually. Python provides a built-in module: os for working with files and directories.

You can access os by loading the module as:

import os

In the topic, we will discuss the basics of os module.

Current working directory

Suppose we have a very simple program divide.py that writes the result of the division of two input numbers to a separate text file:

# divide.py
div_result = int(input()) / int(input())

file = open('division_result.txt', 'w', encoding='utf-8')
file.write(str(div_result))
file.close()

If we store divide.py in a separate PyCharm project, it may be located as /home/user/PycharmProjects/project/divide.py. However, depending on your operating system (especially on Windows), the path can look different.

In the example above, we did not specify the directory where we want to create the file, so when we open the project folder from the PyCharm IDE and launch divide.py, the program will write the text file with the result to the same project directory. It happens because we execute divide.py from the project folder, so it becomes the current working directory. We can check the current working directory using the os.getcwd() function. The result is returned as a string:

print('The current working directory is', os.getcwd())
# The current working directory is /home/user/PycharmProjects/project

Now, assume that we want to launch the program from the command-line interpreter by typing the following statement:

python3 /home/user/PycharmProjects/project/divide.py

The text file will be created in the directory of the Python command-line interpreter. So, it is the home directory. We can similarly check the current working directory from CLI:

python3
# ...
# Type "help", "copyright", "credits" or "license" for more information.
>>>import os
>>>os.getcwd()
# /home/user

The resulting file will be created in different places, depending on the current working directory, the directory where the program is executed. If you don't know it, it can cause problems, so, please, bear it in mind.

Changing the working directory

We can change the working directory manually to avoid confusion. The os.chdir() function can be used for this. It takes the absolute or a relative path as an argument that is basically our desired directory. In the following example, we pass the (absolute) home directory path as a string:

os.chdir('/home/user')

Once we passed the path to chdir(), we can call getcwd() again to make sure that the working directory was changed correctly:

print('The current working directory is', os.getcwd())
# The current working directory is /home/user

The OSError exception (or its subclass) will tell us that the path or filename is not correct.

Creating directories

We may want to create a new directory when working on a piece of code. There are two functions to create new directories — os.mkdir() and os.makedirs().

  • os.mkdir() is used to create a single directory. To do so, we should pass the name of the new folder or the full path to it — so that it will be created in the working directory or in another specified directory, respectively. An example below illustrates the former, we just pass the string some_new_project to mkdir():
    os.mkdir('some_new_project')
  • os.makedirs() allows us to create nested directories in the specified path. Similarly, we can indicate the full path or the names of directories. This function is applied in the following example when creating course, students, and year; year is created within the students directory and students in its turn is created within course.
    os.makedirs('course/students/year')

If a defined directory already exists, FileExistsError will be raised.

Folder content

When working with directories in os, it is very easy to learn about their contents or even change it. We have two functions for that, os.listdir() and os.rename().

  • os.listdir() returns a list of names of all files and folders in the given directory. If not specified, the function will return the list of names for the current working directory.
    print(os.listdir('course'))
    # ['student_list.txt', 'students', 'course_plan.txt']
    It is a very important function. It can be used when you need to process all files in a folder. Note, however, that it returns both file names and folder names, so to get a proper list of files, you'll need to choose only those that end with ".txt" in our example.
  • os.rename() renames the file or the directory to the given name. Its first argument is the path to the text file, the name of which we want to change, and the second argument is the very same path, but with the new name, list_of_students.txt in our example.
    os.rename('course/student_list.txt', 'course/list_of_students.txt')

Conclusion

In this topic, we covered the functions of the os module. The functionality of it is, of course, much larger and you can find the entire list of provided functions in the os module documentation.

Let's briefly sum up the functions we have discussed in the os module:

  • os.getcwd() to learn the current working directory and os.chdir() to change it.
  • os.mkdir() to create a single directory and os.makedirs() to create multiple nested folders.
  • os.listdir() to get the listing of the directory's content and os.rename() to change the name of files and folders.

Now, it's time to practice your new knowledge!

358 learners liked this piece of theory. 6 didn't like it. What about you?
Report a typo