简体   繁体   English

如何删除 python 中的最后一行以将其保持在 10 行

[英]How to remove the last line in python to keep it at exactly 10 lines

I have a text file that already prepends until it has 10 lines我有一个文本文件,它已经前置,直到它有 10 行

    Line 10
    Line 9
    Line 8
    Line 7
    Line 6
    Line 5
    Line 4
    Line 3
    Line 2
    Line 1

Now if I prepend more line into this text file.现在,如果我在此文本文件中添加更多行。 It'll become 11 Line会变成11号线

    Line 11
    Line 10
    Line 9
    Line 8
    Line 7
    Line 6
    Line 5
    Line 4
    Line 3
    Line 2
    Line 1

And now, I want to remove the Line 1 from the file to keep it only 10 lines long.现在,我想从文件中删除第 1 行,使其只有 10 行。 How do I do that in python?我该如何在 python 中做到这一点?

Once you have read your lines, you can use slicing before writing them again with:一旦你阅读了你的行,你可以在再次写入它们之前使用切片:

lines = lines[:10]  # Keep 10 first lines

At first I wrote the code which is Do the writing in file and then I changed it to What you've asked:起初,我编写了在文件中写入的代码,然后将其更改为您所要求的:

For example this is the Code that do the writing:例如,这是编写代码的代码:

f = open("test.txt", "w")

lines = ["line 1 ","line 2","line 3","line 4","line 5","line 6","line 7","line 8","line 9","line 10"]
i = len(lines)-1
while( i >= 0):

    f.write(lines[i]+"\n")
    i -= 1
f.close()

output: output:

line 10
line 9
line 8
line 7
line 6
line 5
line 4
line 3
line 2
line 1 

Now I wanna change this to what you've asked (to delete last line):现在我想将其更改为您要求的内容(删除最后一行):

f = open("test.txt", "w")

lines = ["line 1 ","line 2","line 3","line 4","line 5","line 6","line 7","line 8","line 9","line 10"]

#first of all you have to append new line to you list
lines.append("line 11")
lines = lines[-10:] # this is how you Select 10 last elements

i = len(lines)-1
while( i >= 0):

    f.write(lines[i]+"\n")
    i -= 1


f.close()

Output: Output:

line 11
line 10
line 9
line 8
line 7
line 6
line 5
line 4
line 3
line 2

So as a result for selecting N last elements of list you can use this Option:因此,作为选择列表的最后 N 个元素的结果,您可以使用此选项:

anyList = anyList[-N:]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM