Home > Backend Development > Python Tutorial > python3 method to traverse and delete files with specific suffix names

python3 method to traverse and delete files with specific suffix names

不言
Release: 2018-04-23 17:04:09
Original
2565 people have browsed it

The following is a python3 method for traversing and deleting files with specific suffix names. It has a good reference value and I hope it will be helpful to everyone. Let's come and take a look

The U disk is poisoned. There is an extra .lnk file in each folder in the U disk. Virgo has done it again. I really can't bear it, so I wrote a script to save all the files. The .lnk file was deleted.

Multi-level directory recursive deletion

import os
n = 0
for root, dirs, files in os.walk('./'):
 for name in files:
  if(name.endswith(".lnk")):
   n += 1
   print(n)
   os.remove(os.path.join(root, name))
Copy after login

Save this script as rm.py , then put it in the root directory of the U disk, cd into the root directory of the U disk, and then:

python rm.py

to delete all the files in the U disk. lnk file, including subfolders.

Here you only need to specify the parameters of os.walk(), ./ is the current directory, so that the traversal can traverse all directories and files under the specified path, including multi-level directories. .

To be honest, after finally seeing more than 20 lnk files deleted, I felt extremely satisfied!

Delete the specified file in the current directory

import os
n = 0
for root, dirs, files in os.walk('.'):
 for name in files:
  if("微信截图"in name):
   n += 1
   print(n)
   print(name)
   os.remove(os.path.join(root, name))
Copy after login

The above code will delete the current folder Download all files whose file names contain "WeChat screenshots".

Related recommendations:

How to operate Python to traverse numpy arrays

##

The above is the detailed content of python3 method to traverse and delete files with specific suffix names. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template