python - 错误 - 从列表中保存特定行 | Python
问题描述
基本上我有这段代码复制包含特定单词的行并将它们写入另一个文件。
with open("test.txt", encoding='latin1') as f:
with open("output.txt", "a") as f1:
for line in f:
if str("Hello") in line:
f1.write(str(line.encode('UTF-8')) + "\n")
所以我要做的是从 test.txt 中复制包含“Hello”的行并将它们粘贴到 output.txt 中。例如,输出应如下所示:
你好
他说你好
但是我有这个错误,每行看起来像这样: b'Hello There\n'
我在代码中有 + "\n" 的原因是因为没有它,文件会将它们全部写在一行中。
谁知道怎么修它?:(
解决方案
您不需要将字符串转换为字节并返回,您可以使用
with open("test.txt", encoding='latin1') as f:
with open("output.txt", "a") as f1:
for line in f:
if "Hello" in line:
f1.write(line)
请注意,您不需要在\n
此处添加,因为在读取带有for line in f
.
推荐阅读
- powershell - 使用 powershell 在 Windows 10 中将虚拟目录添加到 IIS 站点
- vue.js - v-select vuetify 最大元素数
- python - 使用 h5py 模块将 Python 列表写入 HDF5 文件
- c# - 我如何处理这个 webapi 项目错误?
- css - 使用 nuxt js 从插件文件中所需的节点模块导入 css
- java - 无缘无故得到 NullPointerException
- xcode - 导出时的 Xcode Catalyst 字体问题
- node.js - 如何在异步函数(aws lambda)中从 dynamodb 读取项目?
- python - 当我尝试使用 np.expand_dim()
- git - 如何使用提交的 http 链接将 gerrit 提交/补丁拉/樱桃选择到分支?