如何删除文件中的特定行? [英] How to delete a specific line in a file?

查看:92
本文介绍了如何删除文件中的特定行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个充满昵称的文本文件.如何使用Python从此文件中删除特定的昵称?

Let's say I have a text file full of nicknames. How can I delete a specific nickname from this file, using Python?

推荐答案

首先,打开文件并从文件中获取所有行.然后以写入模式重新打开文件,然后将行写回,但要删除的行除外:

First, open the file and get all your lines from the file. Then reopen the file in write mode and write your lines back, except for the line you want to delete:

with open("yourfile.txt", "r") as f:
    lines = f.readlines()
with open("yourfile.txt", "w") as f:
    for line in lines:
        if line.strip("\n") != "nickname_to_delete":
            f.write(line)

在比较中,您需要strip("\n")换行符,因为如果文件不以换行符结尾,则最后一个line也不会.

You need to strip("\n") the newline character in the comparison because if your file doesn't end with a newline character the very last line won't either.

这篇关于如何删除文件中的特定行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆