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

-1 python

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

Sea*_*ira 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."
Run Code Online (Sandbox Code Playgroud)

  • 可怕的伪看起来和python一样;) (2认同)