简体   繁体   English

用于选择和删除文件的python脚本

[英]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. 但是我注意到的一件事是,它们都以“ .copy”后缀结尾,因此为了删除它们,我想编写一个python脚本来选择这些文件,然后删除它们。 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 这将从根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. 确认要删除的文件正确后,在第一次运行后删除os.remove.path前面的os.remove.path标签#

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. 希望能奏效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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