python创建文本文件“A.txt”,其中每行包含一段英文,编写程序,读取文件的全部内容,以及一行中包含字符最多和字符最少的分别在第几行。
时间: 2024-03-24 11:36:35 浏览: 15
好的,下面是 Python 的代码实现:
```python
# 创建文件并写入数据
with open('A.txt', 'w') as f:
f.write('Hello, this is the first line.\n')
f.write('The second line is shorter.\n')
f.write('This is the third line, and it has the most characters.\n')
f.write('The fourth line has exactly twenty characters.\n')
max_line = 1
max_count = 0
min_line = 1
min_count = float('inf')
# 读取文件并统计最多和最少字符的行数
with open('A.txt', 'r') as f:
lines = f.readlines()
for i, line in enumerate(lines):
line = line.strip()
count = len(line)
if count > max_count:
max_count = count
max_line = i + 1
if count < min_count:
min_count = count
min_line = i + 1
print('最多字符的行数:', max_line)
print('最少字符的行数:', min_line)
```
运行结果如下:
```
最多字符的行数: 3
最少字符的行数: 2
```
其中,第三行是包含最多字符的行,第二行是包含最少字符的行。注意,为了统计行数,我们使用了 `enumerate` 函数来获取每一行的索引。同时,`strip` 函数可以去掉每一行末尾的换行符。