Home > Article > Backend Development > How to delete a file in Python?
To delete a file, use the remove() method in Python. Pass the name of the file to delete as argument.
Let's first create a file and read the contents: we will display the contents of a text file. To do this, we first create a text file with the following content amit.txt -
Fileamit.txt is visible in the project directory -
Now let us read the contents of the above file
# The file to be read with open("amit.txt", "r") as myfile: my_data = myfile.read() # Displaying the file data print("File data = ",my_data)
File data = Thisisit!
To remove a file, pass the file name and path as arguments to the remove() method. Since the remove() method belongs to the OS module, the OS module is installed and imported first.
To install operating system modules, use the pip command -
pip install os
This is how to import operating system modules in Python after installation -
import os
import os # Delete the file amit.txt print("Deleting our file...") os.remove("amit.txt")
Deleting our file…
We have deleted the above files. The file is now invisible in the project directory -
The above is the detailed content of How to delete a file in Python?. For more information, please follow other related articles on the PHP Chinese website!