python - 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
解决方案
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))
推荐阅读
- python - 如何使用 python 套接字模块向远程计算机发送消息?
- java - ArrayList 底层数组成本
- javascript - React-Navigation:将标题对齐到中心
- python - 如何在 Colab 编辑器中调整 CV2 图像中的图像大小
- html - 从网络下载 R 中的 csv
- javascript - 如何像 Trello 一样重新排列卡片和列表?
- python - 在 tqdm desc 关键字参数中访问 for 循环的成员
- javascript - 未捕获的 ReferenceError:模型未定义
- javascript - 为什么字母表中的所有字母都转换为 Z?
- python - 有没有办法永久添加到 python 中的列表?