Python Advanced Files
Python Advanced Files
This page covers Python advanced files and continues the previous intermediate files tutorial.
For Python intermediate file management here.
It continues the previous intermediate tutorial in more details. Advanced files encompass:
- Deleting files with “os” module
- Deleting directories “os” module
- Deleting files with “pathlib” module
- Deleting directories with “shutil” module
To delete files or folders, Python requires importing built-in modules.
Delete files “os” module
The module “os” is part of the Python built-in modules. It allows developers to interact with the operating system.
And as such, the module provides the method of deleting files.
The following is an example of deleting a file with the module “os”.
x = open("file.txt", "w") x.write("Rewriting text") x.close() x = open("file.txt", "r") print(x.read()) x.close() # Output: Rewriting text
Let’s delete the file.
import os os.remove("file.txt")
Delete directories “os” module
In Python, the “os” module also allows the deletion of folders (directories).
Please note that with the “os” module, Python can delete only empty folders. If the directory contains files, Python produces an error.
Let’s create a new empty folder, named “test”. The following code deletes the empty folder.
import os os.rmdir("test")
Delete files “pathlib” module
The module “pathlib” is another methodology of deleting files.
Please note that “pathlib” requires Python version 3.4 or above.
The code is as follows.
x = open("file.txt", "w") x.write("Rewriting text") x.close() x = open("file.txt", "r") print(x.read()) x.close() # Output: Rewriting text
Let’s delete the file.
import pathlib file = pathlib.Path("file.txt") file.unlink()
First, store the file path in a variable. Then, delete the file with the “unlink()” function of the module.
Delete directories “shutil” module
The module “shutil” is a higher-level module, and as such can delete directories (folders) containing files.
To use the module, first import it.
The following is an example of deleting a folder containing files.
First, create a folder (named “test”). Then, let’s create a file (“file.txt”) inside the folder.
# Attention to the path test/file x = open("test/file.txt", "w") x.write("Rewriting text") x.close() x = open("test/file.txt", "r") print(x.read()) x.close()
Now let’s delete the whole folder (including the file).
import shutil shutil.rmtree("test")
It is important to be careful when managing files, as Python interacts with the operating system. If uncared for, the deletion of vital files may accidentally occur.
Next: Python Advanced Errors