删除文本文件中特定行的Python程序

2024-05-19 21:38:40 发布

您现在位置:Python中文网/ 问答频道 /正文

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

1
2
3
4
5
dy 0.5965
7

现在,我想删除这个文本文件中的第6行。

为此,我使用以下python代码。

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

所以,我把这个文本文件的所有行都保存在“行”中。

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

所以,现在,我有‘t’=‘dy’。现在

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行已从该文本文件中删除)。

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

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

1
2
3
4
5
7

我怎样才能解决这个问题?

我只想使用Python编程来解决这个问题;因为这是一个主要工作的小任务。


Tags: txtcloseifopenuserslines文本文件desktop
3条回答

你应该检查你的逻辑和变量名。每次循环中,您都要检查第[5]行是否不等于第6行。是的,因为正是这条线。要检查当前行:

if t == "dy":
    f = open("C:/Users/Sreeraj/Desktop/Thailand_Rectangle2_National Parks.txt","w")
    for line in lines:
        if line != line6: # <- Check actual line!
            f.write(line)

f.close()

已经指出了这样做的实际错误,但我建议您只比较行号或使用startswith,而不是比较每行的内容。否则,您将进行大量不必要的字符串比较,这可能会造成成本高昂。

其他改进可以是使用with处理文件,只打开一次文件,并允许同时删除多行。

# 'r+' allows you to read and write to a file
with open("C:/Users/Sreeraj/Desktop/Thailand_Rectangle2_National Parks.txt","r+") as f:

    for line in f.readlines():
        if not line.startwith('dy'):
            f.write(line)

    # Truncate the remaining of the file
    f.truncate()

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

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

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)

相关问题 更多 >