2016-08-14 58 views
0

我想遍歷大於100 kb的指定目錄中的文件,並以* .zip結尾。如何使用Python有選擇地迭代文件

這是如何以有效的方式完成的?

會經歷任何zip文件,但不一定大於100kb的文件;

for i in os.listdir(os.getcwd()): 
    if i.endswith(".zip"): 
     ##print i 
     continue 
    else: 
     continue 

如何在if條件下使用它?即(if i.endswith(".zip") and >100kb)。我怎麼能用這個文件作爲myOtherPythonScript.py的參數?

+3

http://stackoverflow.com/questions/2104080/how-to-check-file-size-in-python –

+1

'os.path.getsize'會派上用場...... –

回答

1

你可以嘗試這樣的事情......

for i in os.listdir(os.getcwd()): 
    if i.endswith(".zip"): 
     if os.path.getsize(i) > 10240: 
      print i 
    continue 
else: 
    continue 
+0

怎麼會一個在if語句中使用文件或'i'作爲帶有被調用的python腳本的參數?即在'print i'之後,我將如何使用'i'作爲'myOtherPythonScript.py'的參數。 – 3kstc

+0

您需要將此類設置爲返回I並在myotherpythonscript.py中導入該類的類 – Lance

0

endswithos.path.getsize是你想要的兩個功能。

import os 

file_names = [os.path.join(path, file_name) for file_name in os.listdir(path)] 
for file_name in file_names: 
    if file_name.endswith('zip') and os.path.getsize(file_name) >= 100*1024: 
     pass 
    else: 
     pass