2010-10-16 118 views

回答

57

這確實目錄及其所有子目錄:

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) 
-2

一般ls -la是以字節爲單位。

如果您想以「人類可讀」形式使用,請使用命令ls -alh

31

你也可以使用find

find /path -type f -size -200k -delete 
+2

這是關於Python中的問題,答案應該保持在同一個域中 – unixo 2014-10-13 08:03:55

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 
相關問題