Python脚本遍历目录中所有文件并删除小于200 kB的文件

31 投票
4 回答
52861 浏览
提问于 2025-04-16 05:34

我想删除一个文件夹里所有小于200千字节(kB)的文件。

我想确认一下,当我在我的MacBook上用命令ls -la查看文件时,文件大小显示的是171或143,我可以认为这是以千字节为单位的,对吧?

4 个回答

28

你也可以使用

import os    

files_in_dir = os.listdir(path_to_dir)
for file_in_dir in files_in_dir:
    #do the check you need on each file
31

你也可以使用 find 命令。

find /path -type f -size -200k -delete
60

这个代码会处理当前目录以及所有的子目录:

import os, os.path

for root, _, files in os.walk(dirtocheck):
    for f in files:
        fullpath = os.path.join(root, f)
        if os.path.getsize(fullpath) < 200 * 1024:
            os.remove(fullpath)

或者:

import os, os.path

fileiter = (os.path.join(root, f)
    for root, _, files in os.walk(dirtocheck)
    for f in files)
smallfileiter = (f for f in fileiter if os.path.getsize(f) < 200 * 1024)
for small in smallfileiter:
    os.remove(small)

撰写回答