python - 导入 txt 文件并将行反转作为输出
问题描述
我是 python 新手,想知道如何设置一个函数来接受文件作为参数,但输出应该会产生它 inn 反转行
例如,如果文本文件包含以下内容:
"Jack and Jill went up the hill
to fetch a pail of water
jack fell down and broke his crown"
输出应该是
"to fetch a pail of water
jack fell down and broke his crown
Jack and Jill went up the hill"
解决方案
代码
with open('test.txt', 'r') as fr, open('test_out.txt', 'w') as fw:
content = fr.readlines()
for item in content[::-1]:
fw.write("%s\n" % item.rstrip('\n'))
输入文件
Jack and Jill went up the hill
to fetch a pail of water
jack fell down and broke his crown
输出文件
jack fell down and broke his crown
to fetch a pail of water
Jack and Jill went up the hill
推荐阅读
- r - R:满足条件时向数据框添加新行,然后重复最终值
- c - 我在此代码中出现错误,在数字常量之前预期为 ';'、',' 或 ')'|
- java - java.lang.NullPointerException:空对象引用上的'boolean java.lang.String.equals(java.lang.Object)'
- tensorflow - 我安装了 CUDA 和 CUDNN,但仍然出现此错误
- java - 卡片组中卡片的 ImageView
- python - 如何使用来自 CNN Business 的 lxml 下载图像
- sql - 删除版本 3.22.0 的 SQLite 中除一个重复行之外的所有重复行?
- javascript - 反应 - 我的
- javascript - 不允许从 React 对 Django API 的请求
- ios - SwiftUI iOS 13 ZStack 的行为与 iOS 14 不同