Change language

How do I delete files in Python?

| | |

delete file

In our tutorial on working with files in Python we learned how to manage them. In this tutorial, we will learn how to delete files in Python.

Let’s assume that after successfully creating a file, we perform some operations on it, such as reading and writing. Once we have finished using the file to analyze various datasets, it may be that in some cases we will not need it in the future.



 

Let’s take a look at the different ways in which we can delete files in Python.

1 Using the os module

The os module in Python provides several easy to use methods with which we can delete or delete a file as well as an empty directory. Take a close look at the code below:

 import os if os.path.isfile (’/ Users / test / new_file.txt’): os .remove (’/ Users / test / new_file.txt’) print (" success ") else: print (" File doesn’t exists! ") 

Here we used the if-else statement to avoid the exception that can be thrown if the file directory does not exist. The isfile () method checks for the existence of a file with the filename && # 8216; new_file.txt & # 8217 ;.

Again, the os module provides us with another method, rmdir () , which can be used to deleting or deleting an empty directory. For example:

 import os os.rmdir (’directory’) 

Note: the directory must be empty. If it contains any content, the method returns an OSerror.



2 Usage shutil module

Shutil &this is another file deletion method that allows the user to easily delete a file or its entire directory (including all its contents).

rmtree () &it is a method of the shutil module that recursively deletes a directory and its contents. Let’s see how to use it:

 import shutil shutil.rmtree (’/ test /’) 

For the above code deleted directory / test /. Most importantly, all content inside the directory is also removed.

3 Using the pathlib module

pathlib &this is a built-in Python module available for Python 3.4+.

Here’s an example:

 import pathlib file = pathlib.path ( "test / new_file.txt") file.unlink () 

In the above example, the path () method is used to get the file path, while the unlink ( ) is used to unlink or delete a file at the specified path.

The unlink () method works with files. If a directory is specified, an OSError is thrown. To remove a directory, we can use one of the previously discussed methods.

References

  • https: //docs.pytho n.org/3/library/os. html # os.remove
  • https://docs.python.org/3/library/shutil.html
  • https://docs.python.org/3/library/ pathlib.html



Shop

Learn programming in R: courses

$

Best Python online courses for 2022

$

Best laptop for Fortnite

$

Best laptop for Excel

$

Best laptop for Solidworks

$

Best laptop for Roblox

$

Best computer for crypto mining

$

Best laptop for Sims 4

$

Latest questions

NUMPYNUMPY

Common xlabel/ylabel for matplotlib subplots

12 answers

NUMPYNUMPY

How to specify multiple return types using type-hints

12 answers

NUMPYNUMPY

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

12 answers

NUMPYNUMPY

Flake8: Ignore specific warning for entire file

12 answers

NUMPYNUMPY

glob exclude pattern

12 answers

NUMPYNUMPY

How to avoid HTTP error 429 (Too Many Requests) python

12 answers

NUMPYNUMPY

Python CSV error: line contains NULL byte

12 answers

NUMPYNUMPY

csv.Error: iterator should return strings, not bytes

12 answers

News


Wiki

Python | How to copy data from one Excel sheet to another

Common xlabel/ylabel for matplotlib subplots

Check if one list is a subset of another in Python

sin

How to specify multiple return types using type-hints

exp

Printing words vertically in Python

exp

Python Extract words from a given string

Cyclic redundancy check in Python

Finding mean, median, mode in Python without libraries

cos

Python add suffix / add prefix to strings in a list

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

Python - Move item to the end of the list

Python - Print list vertically