2012-12-04 75 views
0

我想根據它們的大小對文件進行排序並將日誌存儲在文件中。但是我收到一個錯誤,說'getsize'沒有定義。請幫我解決這個問題。Python:getsize not defined

from ClientConfig import ClientConfig 
import os 
import os.path 

class VerifyFileNSize: 
    def __init__(self): 
     self.config = ClientConfig() 
     self.parseInfo() 

    def parseInfo(self): 
     count = 0 
     size = 0 
     sort_file = [] 
     originalPath = os.getcwd() 
     os.chdir(self.config.Root_Directory_Path())  
     log = open(self.config.File_Count(),'wb')   
     for root, dirs, files in os.walk("."):    
      for f in files: 
       sort_file.append(os.path.join(root, f)) 

     sorted_file = sorted(sort_file, key=getsize) 

     for f in sorted_file: 
      log.write((str(os.path.getsize(f)) + " Bytes" + "|" + f +   os.linesep).encode())     
      size += os.path.getsize(f) 
      count += 1 
     totalPrint = ("Client: Root:" + self.config.Root_Directory_Path() + " Total  Files:" + str(count) + " Total Size in Bytes:" + str(size) + " Total Size in  MB:" + str(round(size /1024/1024, 2))).encode() 
     print(totalPrint.decode()) 
     log.write(totalPrint) 
     log.close() 
     os.chdir(originalPath) 

if __name__ == "__main__": 
    VerifyFileNSize() 

回答

1

getsize沒有在調用sorted的名稱空間中定義。這是在模塊os.path,你導入的功能,讓你可以參考這樣的:

sorted_file = sorted(sort_file, key=os.path.getsize) 

另一種可能性是要做到:

from os.path import join, getsize 

甚至:

from os.path import * 

這將允許你這樣做:

sorted_file = sorted(sort_file, key=getsize) 

但最後一個選項並不是真正的建議,您應該嘗試只導入您真正需要的名稱。

1

嘗試前面加上os.path

sorted_file = sorted(sort_file, key=os.path.getsize) 
            ^^^^^^^^ 

或者,你可以只說from os.path import getsize

1

如果由於某種原因沒有這些答案的工作,總是有:

sorted_file = sorted(sort_file, key=lambda x: os.path.getsize(x)) 
+0

這是沒有必要的 – piokuc