2012-12-04 73 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