# 打开文件with open('words.txt', 'r') as f: # 读取所有行 lines = f.readlines() # 将要添加的单词添加到行末 new_words = ['baa', 'babble', 'babbler', 'babe', 'babel', 'baboon', 'baby', 'babyhood', 'Babylon', 'Babylonian'] lines.extend('\n' + word for word in new_words) # 统计文件总行数 num_lines = len(lines) # 统计最长单词的长度 max_length = max(len(line.strip()) for line in lines) # 统计首字母为大写A的单词 A_words = [line.strip() for line in lines if line.startswith('A') and line[1].isupper()] # 将长度超过10的单词写入新文件 with open('long_words.txt', 'w') as f_long: for line in lines: if len(line.strip()) > 10: f_long.write(line)# 将修改后的内容写回原文件with open('words.txt', 'w') as f: f.writelines(lines)# 输出结果print('文件总行数为:', num_lines)print('最长单词的长度为:', max_length)print('首字母为大写A的单词为:', A_words)print('长度超过10的单词已写入新文件long_words.txt')写出其运行代码
时间: 2023-08-12 10:03:23 浏览: 53
以下是完整的Python程序代码:
```python
# 打开文件
with open('words.txt', 'r') as f:
# 读取所有行
lines = f.readlines()
# 将要添加的单词添加到行末
new_words = ['baa', 'babble', 'babbler', 'babe', 'babel', 'baboon', 'baby', 'babyhood', 'Babylon', 'Babylonian']
lines.extend('\n' + word for word in new_words)
# 统计文件总行数
num_lines = len(lines)
# 统计最长单词的长度
max_length = max(len(line.strip()) for line in lines)
# 统计首字母为大写A的单词
A_words = [line.strip() for line in lines if line.startswith('A') and line[1].isupper()]
# 将长度超过10的单词写入新文件
with open('long_words.txt', 'w') as f_long:
for line in lines:
if len(line.strip()) > 10:
f_long.write(line)
# 将修改后的内容写回原文件
with open('words.txt', 'w') as f:
f.writelines(lines)
# 输出结果
print('文件总行数为:', num_lines)
print('最长单词的长度为:', max_length)
print('首字母为大写A的单词为:', A_words)
print('长度超过10的单词已写入新文件long_words.txt')
```