简体   繁体   中英

python script for selecting and deleting files

I accidently made copies of a lot of files on my computer. But one thing I noticed was that they all ended with the suffix ".copy", so in order to delete them I would like to write a python script to select these files and then deleting them. How do i go about doing that?

import os

dir = 'C:\\Path\\To\\Directory' # if using Windows
#dir = '/path/to/directory'  # if using Linux/OS X

files = [os.path.join(dir, f) for dir, subdir, files in os.walk(dir) for f in files if f.endswith('.copy')]

for f in files:
    print f
    # os.remove.path(f)

This will iterate through all files and folders starting at the root dir

Remove the hash tag # in front of os.remove.path after the first run once you've verified the correct files are being removed.

import os
for file_name in os.listdir("path/to/the/folder_with_files"):
    if file_name.endswith('.copy'):
        os. delete(file_name)

Hopes that work.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM