【问题标题】:Python - Performing a comparative function on all files in a directoryPython - 对目录中的所有文件执行比较功能
【发布时间】:2015-04-07 02:43:13
【问题描述】:

我有一个函数可以找到字符串的平均长度...

 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 文件。任何帮助都会很棒,尤其是如何比较目录中的所有文件。谢谢。

【问题讨论】:

    标签: python directory python-import


    【解决方案1】:
    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

    【讨论】:

      猜你喜欢
      • 2016-02-08
      • 2013-10-28
      • 2015-02-01
      • 2012-05-18
      • 1970-01-01
      • 2013-12-13
      相关资源
      最近更新 更多