How can I delete all files in a directory but keep all its sub-directories intact?
Starting with a directory like:
root
|-- somedir
| |-- file1.txt
| |-- file2.txt
| |-- deleteme.ext
| |-- subfolder1
| | |-- important_file.dbf
| |-- subfolder2
| | |-- business_critical.xls
I want to end up with
root
|-- somedir
| |-- subfolder1
| | |-- important_file.dbf
| |-- subfolder2
| | |-- business_critical.xls
You can use os.listdir()
and os.path.isfile()
:
files = [f for f in os.listdir(path) if os.path.isfile(os.path.join(path,f))]
for fname in files:
fpath = os.path.join(path, fname)
os.remove(fpath)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.