Python 脚本循环遍历目录中的所有文件,删除任何小于 200 kB 的文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3947313/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python script to loop through all files in directory, delete any that are less than 200 kB in size
提问by Blankman
I want to delete all files in a folder that are less than 200 kB in size.
我想删除文件夹中小于 200 kB 的所有文件。
Just want to be sure here, when i do a ls -la on my macbook, the file size says 171 or 143, I am assuming this is kb correct?
只是想确定一下,当我在我的 macbook 上执行 ls -la 时,文件大小显示为 171 或 143,我假设这是正确的 kb?
采纳答案by hughdbrown
This does directory and all subdirectories:
这是目录和所有子目录:
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)
Or:
或者:
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)
回答by Thomas
Generally ls -lais in bytes.
一般ls -la以字节为单位。
If you want it in "human readable" form, use the command ls -alh.
如果您希望它以“人类可读”的形式出现,请使用命令ls -alh.
回答by ghostdog74
you can also use find
你也可以使用 find
find /path -type f -size -200k -delete
回答by TheMeaningfulEngineer
You could also use
你也可以使用
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

