.remove()
Anonymous contributor
Anonymous contributor9 total contributions
Anonymous contributor
Published Apr 1, 2022Updated Aug 6, 2023
Contribute to Docs
The Python .remove()
file method allows the user to delete a file if it exists in the system or computer. .unlink()
is an alternative to delete a file.
Note: A FileNotFoundError
is raised if the file is not found or isn’t in the current directory.
Syntax
This method is provided by the os
module which must be imported beforehand.
import os
os.remove("file_name.file_type")
os.remove("file_path")
The .remove()
method works in the following ways:
- If the file exists in the current directory, a string argument for the file (written as
"file_name.file_type"
) can be used to successfully delete it. - A
"file_path"
can also be passed if a file exists outside the current directory.
Entire folders or directories can be removed using the .rmdir()
method.
Example
In the example below, the .remove()
method is used to delete the my_file.txt
file:
import os# Delete file in current directoryos.remove("my_file.txt")# Delete file in another directoryos.remove("path/to/my_file.txt")
Codebyte Example
The example below creates a file called example.txt
and then deletes it using the .remove()
method. The .isfile()
method is used to show at which stage the file is found.
All contributors
- Anonymous contributorAnonymous contributor9 total contributions
- Anonymous contributorAnonymous contributor15 total contributions
- Christine_Yang271 total contributions
- net137228473814 total contributions
- Anonymous contributor
- Anonymous contributor
- Christine_Yang
- net1372284738
Looking to contribute?
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.