2015-04-07 46 views
0

我有找到字符串的平均長度的函數...Python的 - 在一個目錄下的所有文件執行比較功能

def mean_length(sequence): 
    sum = 0.0 
    nonblank = 0 
    for string in sequence: 
     if string.strip(): 
      sum = sum + len(string) 
      nonblank = nonblank + 1 
    return sum/nonblank 

我有麻煩創建一個新的功能,將找到.txt文件與其他所有.txt文件相比,具有最高平均字符串長度的目錄。任何幫助都會很棒,特別是如何比較目錄中的所有文件。謝謝。

回答

0
path = # This will be the path to the directory from your current working driectory 

import glob 
files = glob.glob(path + '*.txt') # This returns a list containing all files that are in the path that end in ".txt" 
for file in files: 
    # Do what you need to do here for each file 

https://docs.python.org/2/library/glob.html

相關問題