使用python删除文本文件中的换行符

2024-04-28 03:26:49 发布

您现在位置: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

Modified-a.txt使用上述代码,可以删除mango关键字行,但是我想进一步删除orangegrapes之间的空格

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

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


Tags: 代码intxtappleforaswithcontents
1条回答
网友
1楼 · 发布于 2024-04-28 03:26:49

循环行,检查第一个字段是否为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")

相关问题 更多 >