首页 > 解决方案 > Output features of a file based on its longest line

问题描述

I want to write a program file_stats.py that when run on the command line, accepts a text file name as an argument and outputs the number of characters, words, lines, and the length (in characters) of the longest line in the file. Does anyone know the proper syntax to do something like this if I want the output to look like this:

Characters: 553
Words: 81
Lines: 21
Longest line: 38

标签: pythonpython-3.x

解决方案


Assuming your file path is a string, something like this should work

file = "pathtofile.txt"

with open(file, "r") as f:
    text = f.read()
    lines = text.split("\n")
    longest_line = 0
    for l in lines:
        if len(l) > longest_line:
            longest_line = len(l)
print("Longest line: {}".format(longest_line))

推荐阅读