Python - 对目录中的所有文件执行比较功能
Python - Performing a comparative function on all files in a directory
我有一个函数可以计算字符串的平均长度...
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 文件。任何帮助都会很棒,特别是如何比较目录中的所有文件。谢谢
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
我有一个函数可以计算字符串的平均长度...
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 文件。任何帮助都会很棒,特别是如何比较目录中的所有文件。谢谢
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