我想刪除文件夾中小於200 kB大小的所有文件。Python腳本循環遍歷目錄中的所有文件,刪除大小小於200 kB的任何文件
只想在這裏確定,當我在我的MacBook上做ls -la時,文件大小爲171或143,我假設這是kb正確的?
我想刪除文件夾中小於200 kB大小的所有文件。Python腳本循環遍歷目錄中的所有文件,刪除大小小於200 kB的任何文件
只想在這裏確定,當我在我的MacBook上做ls -la時,文件大小爲171或143,我假設這是kb正確的?
這確實目錄及其所有子目錄:
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)
一般ls -la
是以字節爲單位。
如果您想以「人類可讀」形式使用,請使用命令ls -alh
。
你也可以使用find
find /path -type f -size -200k -delete
你也可以使用
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
這是關於Python中的問題,答案應該保持在同一個域中 – unixo 2014-10-13 08:03:55