1

This is my code to delete last line of file but after rewriting it to the same file there is an extra empty line that exist.

lines = open('file.csv', 'r').readlines() 
del lines[-1] 
open('file.csv', 'w').writelines(lines) 

Notice that initial file has two lines: Initial File

 Orange[1st line of csv]
 Blue[2nd line of csv]

Notice that the last text/line of file is deleted, but there is extra empty line: enter image description here

 Orange[1st line of csv]
 [2nd line still exist but empty]

My goal is to have that extra line to be deleted. Thank you in advance!

Community
  • 1
  • 1
bumbumpaw
  • 2,522
  • 1
  • 24
  • 54
  • 1
    A well-formed text file always has a trailing newline on each line. In some sense this produces an "empty string" which can be rendered as a line with no content at the very end of the file in some programs. It's not really clear from your question if this is what concerns you; if it is, my advice would be to not worry about it. Not writing a newline at the end of the last line is technically trivial, but usually not a good idea if you want your text files to be interoperable with other programs. – tripleee Apr 06 '19 at 15:22
  • @tripleee, if my program need to rewrite again on the same file, my concern is that I got Orange[1st line] Empy line[2nd line] and then New Color[3rd line], this shows that I ended up with some empty lines – bumbumpaw Apr 06 '19 at 15:29

1 Answers1

1

The reason is that the newline is not from the line with 'Orange', but rather from the line with 'Blue', which is in fact 'Blue\n'.

Accordingly, you should do something like this:

with open('file.csv', 'r+') as f:
    lines = f.readlines()[:-1]
    lines[-1] = lines[-1].strip()
    f.seek(0)
    f.writelines(lines)
    f.truncate()

Note, in particular:

  • The use of with to open files to prevent leaking file objects
  • A single call to open in read/write mode (this is more of a matter of style)

Contents of file.csv:

Blue
gmds
  • 19,325
  • 4
  • 32
  • 58
  • I tried befoew the strip(), except for adding f.seek and f.truncate, I will check further for what it does, – bumbumpaw Apr 06 '19 at 15:38
  • 1
    @bumbumpaw the file object you get when you call `open` maintains a pointer to the current position in the file. After reading, the pointer is at the end, so you need to go back to the beginning with `seek` to begin writing. When `write` is called, you overwrite *what is already there*, so when you're done you need to call `truncate` to remove the rest of the old data, if any. – gmds Apr 06 '19 at 23:14