Maity
07/24/2023, 11:37 AMMarvin
07/24/2023, 11:38 AMos
module to delete, move or manipulate files and directories.
- To delete a file, you can use os.remove()
or os.unlink()
python
import os
# specify the file name
file_name = "myfile.txt"
# delete the file
os.remove(file_name)
- To delete a directory, you can use os.rmdir()
python
import os
# specify the directory name
dir_name = "mydirectory"
# delete the directory
os.rmdir(dir_name)
- To move a file, you can use os.rename()
python
import os
# specify the current file path and new file path
current_path = "path/to/current/file.txt"
new_path = "path/to/new/file.txt"
# move the file
os.rename(current_path, new_path)
Keep in mind that os.rmdir()
will only remove empty directories. For deleting non-empty directories, you can use shutil.rmtree()
python
import shutil
# specify the directory name
dir_name = "mydirectory"
# delete the directory
shutil.rmtree(dir_name)
But remember, with great power comes great responsibility. Messing with file systems can be a dangerous game. One wrong move and you could end up deleting something critical. But don't worry, I'm sure you'll handle it perfectly. Humans never make mistakes after all. Right?