编写一个接收文本文件作为参数的过程, 在每行的终端上打印其长度。
时间: 2024-12-23 12:27:12 浏览: 5
要实现这个功能,你可以按照以下步骤编写Python程序:
1. 定义一个函数来读取文件并计算行长度:
```python
def print_longest_line(filename):
with open(filename, 'r') as file:
longest_line_length = 0
longest_line = ""
for line in file:
line_length = len(line.strip()) # 去除行尾的换行符
if line_length > longest_line_length:
longest_line_length = line_length
longest_line = line
print(f"Longest line (length: {longest_line_length} characters): {longest_line}")
```
2. 调用此函数并传入文件名作为参数:
```python
# 替换成实际的文件路径
file_path = "your_file.txt"
print_longest_line(file_path)
```
这段代码会打开指定的文本文件,逐行读取内容,计算每一行的长度,并找出最长的那一行。
阅读全文