如何计算给定目录中文件的总行数?在python中

时间:2011-02-18 17:31:42

标签: python

如何使用Python计算给定目录中文件的总行数?

2 个答案:

答案 0 :(得分:5)

在伪代码(不可执行)中:

total_length = 0
file_list = fetch_file_list() 
# USE: os.walk or glob.glob depending on whether you want to filter the files.
for file_path in file_list:
    file_path = make_path_absolute(file_path)
    # This can be as simple as os.path.join(your_root_path, file_path)
    file_object = open(file_path) 
    # Don't forget there are different modes -- will all the files be text?
    total_length += length(file_object.readlines()) 
    # YOU MIGHT WANT TO CONSIDER: What if some of the files are large?
print "There are", length(file_list), "files in", \
    file_path, "containing", total_length, "lines of text."

答案 1 :(得分:0)

查看Python OS以获取文件列表。