Python程序删除文本文件中的特定行 [英] Python program to delete a specific line in a text file

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

问题描述

我有一个包含以下几行的文本文件 Thailand_Rectangle2_National Parks.txt.

I have a text file Thailand_Rectangle2_National Parks.txt with the following lines.

1
2
3
4
5
dy 0.5965
7

现在,我想删除此文本文件中的第 6 行.

Now, I want to delete the 6th line in this text file.

为此,我使用了以下 python 代码.

For that, I am using the following python code.

f = open("C:/Users/Sreeraj/Desktop/Thailand_Rectangle2_National Parks.txt","r")
lines = f.readlines()

因此,我将这个文本文件的所有行保存在行"中.

So, I saved all the lines of this text file in 'lines'.

line6 = lines[5]
t = line6[:2]
f.close() 

所以,现在,我有 't' = "dy" .现在,

So, now, I have 't' = "dy" . Now,

if t == "dy":
    f = open("C:/Users/Sreeraj/Desktop/Thailand_Rectangle2_National Parks.txt","w")
    for line in lines:
        if lines[5] != line6:
            f.write(line)

f.close()

所以,如果条件 't' = "dy" 满足,那么我将打开此文本文件进行写入,并将打印除第 6 行之外的所有行(这意味着从该文本文件中删除了第 6 行).

So, if the condition 't' = "dy" satisfies, then I will open this text file for writing and I will print all the lines except line6 (which means line6 is deleted from this text file).

不幸的是,我得到这个文本文件中的行为空白,这意味着没有行被打印为输出.

Unfortunately, I am getting the lines in this text file as blank, which means no lines are printed as outputs.

但是,我希望文本文件中的行如下所示.

But, I want the lines in the text file as given below.

1
2
3
4
5
7

我该如何解决这个问题?

How can I solve this issue ?

我只想用Python编程来解决这个问题;因为这是一项大工程的小任务.

I want to use only Python programming to solve this issue; since this is a small task of a major work.

推荐答案

你的问题是 lines[5]always 等于 line6.您从未修改过 lines 中的第六行,因此 line6lines[5] 仍然相等.因此,条件 lines[5] != line6 将始终失败.

Your problem is that lines[5] will always be equal to line6. You never modified the sixth line in lines, so line6 and lines[5] are still equal. Thus, the condition lines[5] != line6 will always fail.

如果您想始终从文件中删除第六行,您可以使用 enumerate.例如:

If you want to always remove the sixth line from your file, you can use enumerate. For example:

with open("file.txt", "r") as infile:
    lines = infile.readlines()

with open("file.txt", "w") as outfile:
    for pos, line in enumerate(lines):
        if pos != 5:
            outfile.write(line)

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

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