Delete final line in file with python

2019-01-13 13:06发布

How can one delete the very last line of a file with python?

Input File example:

hello
world
foo
bar

Output File example:

hello
world
foo

I've created the following code to find the number of lines in the file - but I do not know how to delete the specific line number. I'm new to python - so if there is an easier way - please tell me.

    try:
        file = open("file")
    except IOError:
        print "Failed to read file."
    countLines = len(file.readlines())

EDIT:

I figured it out using a variety of answers: Mostly Strawberry's and something I saw in the web (sorry, I can't find the link).

#!/usr/bin/env python

import os, sys

readFile = open("file")

lines = readFile.readlines()

readFile.close()
w = open("file",'w')

w.writelines([item for item in lines[:-1]])

w.close()

标签: python text line
10条回答
在下西门庆
2楼-- · 2019-01-13 13:49

You could use the above code and then:-

lines = file.readlines()
lines = lines[:-1]

This would give you an array of lines containing all lines but the last one.

查看更多
兄弟一词,经得起流年.
3楼-- · 2019-01-13 13:49

Assuming you have to do this in Python and that you have a large enough file that list slicing isn't sufficient, you can do it in a single pass over the file:

last_line = None
for line in file:
    if last_line:
        print last_line # or write to a file, call a function, etc.
    last_line = line

Not the most elegant code in the world but it gets the job done.

Basically it buffers each line in a file through the last_line variable, each iteration outputs the previous iterations line.

查看更多
三岁会撩人
4楼-- · 2019-01-13 13:55

Because I routinely work with many-gigabyte files, looping through as mentioned in the answers didn't work for me. The solution I use:

file = open(sys.argv[1], "r+", encoding = "utf-8")

#Move the pointer (similar to a cursor in a text editor) to the end of the file. 
file.seek(0, os.SEEK_END)

#This code means the following code skips the very last character in the file - 
#i.e. in the case the last line is null we delete the last line 
#and the penultimate one
pos = file.tell() - 1

#Read each character in the file one at a time from the penultimate 
#character going backwards, searching for a newline character
#If we find a new line, exit the search
while pos > 0 and file.read(1) != "\n":
    pos -= 1
    file.seek(pos, os.SEEK_SET)

#So long as we're not at the start of the file, delete all the characters ahead of this position
if pos > 0:
    file.seek(pos, os.SEEK_SET)
    file.truncate()

file.close()
查看更多
狗以群分
5楼-- · 2019-01-13 13:55

here is my solution for linux users:

import os 
file_path = 'test.txt'
os.system('sed -i "$ d" {0}'.format(file_path))

no need to read and iterate through the file in python.

查看更多
beautiful°
6楼-- · 2019-01-13 13:58

On systems where file.truncate() works, you could do something like this:

file = open('file.txt', 'rb')
pos = next = 0
for line in file:
  pos = next # position of beginning of this line
  next += len(line) # compute position of beginning of next line
file = open('file.txt', 'ab')
file.truncate(pos)

According to my tests, file.tell() doesn't work when reading by line, presumably due to buffering confusing it. That's why this adds up the lengths of the lines to figure out positions. Note that this only works on systems where the line delimiter ends with '\n'.

查看更多
欢心
7楼-- · 2019-01-13 13:59

This doesn't use python, but python's the wrong tool for the job if this is the only task you want. You can use the standard *nix utility head, and run

head -n-1 filename > newfile

which will copy all but the last line of filename to newfile.

查看更多
登录 后发表回答