This article describes how to delete files and directories in python. Share with everyone for your reference. The specific implementation method is as follows:
os.remove(path)
Delete file path. If path is a directory, OSError will be thrown. If you want to delete a directory, use rmdir().
remove() has the same function as unlink()
In Windows, deleting a file in use will throw an exception. In Unix, the records in the directory table are deleted, but the file storage is still there.
# Use os.unlink()And os.remove()To delete files
#! /user/local/bin/python2.7
# - *- coding:utf-8-*-import os
my_file ='D:/text.txt'if os.path.exists(my_file):
# To delete files, you can use the following two methods.
os.remove(my_file)
# os.unlink(my_file)else:
print 'no such file:%s'%my_file
**os.removedirs(path) **
Delete directories recursively. Similar to rmdir(), if the subdirectory is successfully deleted, removedirs() will delete the parent directory; but the subdirectory is not successfully deleted, an error will be thrown.
For example, os.removedirs("foo/bar/baz") will delete the "foo/bar/ba" directory first, then delete foo/bar and foo, if they are empty
If the subdirectory cannot be deleted successfully, an OSError exception will be thrown
os.rmdir(path)
To delete the directory path, the path must be an empty directory, otherwise OSError will be thrown
Recursively delete directories and files (similar to the DOS command DeleteTree):
Copy the code code as follows:
import os
for root, dirs, files in os.walk(top, topdown=False):for name in files:
os.remove(os.path.join(root, name))for name in dirs:
os.rmdir(os.path.join(root, name))
Method 2:
code show as below
import shutil
shutil.rmtree()
Example extension:
Python os.unlink() method
The os.unlink() method is used to delete a file, and an error is returned if the file is a directory.
The following example demonstrates the use of the unlink() method:
#! /usr/bin/python
# - *- coding: UTF-8-*-import os, sys
# List directories
print "The directory is: %s"%os.listdir(os.getcwd())
os.unlink("aa.txt")
# Deleted directory
print "The deleted directory is: %s"%os.listdir(os.getcwd())
The directory is:
[ ‘a1.txt’,’aa.txt’,’resume.doc’]
The deleted directory is:
[ ‘a1.txt’,’resume.doc’ ]
So far, this article on how to delete files and directories in python is introduced. For more related methods of deleting files and directories in python, please search for the previous articles of ZaLou.Cn or continue to browse the related articles below. Hope you will support more in the future ZaLou.Cn!
Recommended Posts