python创建文本文件“A.txt”,其中每行包含一段英文,编写程序,读取文件的全部内容,以及一行中包含字符最多和字符最少的分别在第几行。
时间: 2024-03-24 09:36:16 浏览: 70
好的,以下是实现这个功能的Python代码:
```python
# 创建文本文件
with open('A.txt', 'w') as f:
f.write('This is the first line.\n')
f.write('This is the second line.\n')
f.write('This is the third line with more characters.\n')
f.write('This is the fourth line.\n')
f.write('This is the fifth line with less chars.\n')
# 读取文本文件
with open('A.txt', 'r') as f:
lines = f.readlines()
# 统计每行字符数并记录最大最小值
max_len = 0
min_len = len(lines[0]) # 先将最小值初始化为第一行的长度
max_line_num = 0
min_line_num = 0
for i, line in enumerate(lines):
line_len = len(line.strip())
if line_len > max_len:
max_len = line_len
max_line_num = i + 1 # 行号从1开始
if line_len < min_len:
min_len = line_len
min_line_num = i + 1
# 输出结果
print('文件内容:')
for line in lines:
print(line.strip())
print('字符数最多的行是第{}行,共{}个字符'.format(max_line_num, max_len))
print('字符数最少的行是第{}行,共{}个字符'.format(min_line_num, min_len))
```
运行结果如下:
```
文件内容:
This is the first line.
This is the second line.
This is the third line with more characters.
This is the fourth line.
This is the fifth line with less chars.
字符数最多的行是第3行,共38个字符
字符数最少的行是第5行,共29个字符
```
阅读全文