首页 > 解决方案 > 使用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

任何帮助或建议都会很棒。提前致谢。

标签: python

解决方案


遍历这些行,检查第一个字段是否为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")

推荐阅读