python - 使用python删除文本文件中的换行符
问题描述
我正在使用的代码是
for fruits, u_list in d.items():
with open(fruits, "r") as f:
contents = f.read().strip()
for id in u_list:
contents = re.sub(id+".*","", contents)
with open(fruits, "w") as f:
f.write(contents)
原文 - a.txt
apple,2019/03/31
orange,2020/08/18
mango,2020/09/15
grapes,2017/01/08
black.plum,2018/03/13
修改 - a.txt使用上面的代码,能够删除mango
关键字行,但是我想进一步删除 and 之间的orange
空格grapes
。
apple,2019/03/31
orange,2020/08/18
grapes,2017/01/08
black.plum,2018/03/13
预期 - a.txt
apple,2019/03/31
orange,2020/08/18
grapes,2017/01/08
black.plum,2018/03/13
任何帮助或建议都会很棒。提前致谢。
解决方案
遍历这些行,检查第一个字段是否为d[file]
,如果是则跳过该行。
for file, word in d.items():
with open(f"{file}.txt", "r") as f:
contents = f.read().strip().splitlines()
with open(f"{file}.txt", "w") as f:
for line in contents:
if line.split(',')[0] != word:
f.write(line + "\n")
推荐阅读
- c++ - 将 MQL4 转换为 C++?
- sql - 如何在oracle中将大数(130位)修剪为40位
- bash - 如何使用 each 表达式连接 Azure Pipelines 中的 bash 脚本
- php - 从 PHP7.4 迁移到 PHP8.0 后数据库连接不起作用
- javascript - 将 Puppeteer 日志结果传递到表单输入字段
- r - 如何基于 r 中的两列创建序列数值列?
- r - 具有大型数据集(>100 万行)的广义加性混合效应模型 (GAMM)
- python-3.x - python中的二分网络
- mongodb - Digital Ocean 液滴中的 MongoDB 连接错误
- flutter - 在颤振中创建自定义条子应用栏很热门