January 2019
Beginner
318 pages
8h 23m
English
We will learn how to delete files and folders using the os module in Python. The remove() method of the os module will delete a file. If you try to remove a directory using this method, it will give you an OSError. To remove directories, use rmdir().
Now, create a os_remove_file_directory.py script and write the following content in it:
import osos.remove('sample.txt')print("File removed successfully")os.rmdir('work1')print("Directory removed successfully")
Run the script as follows:
$ python3 os_remove_file_directory.pyOutput:File removed successfullyDirectory removed successfully
Read now
Unlock full access