1

So,I have this problem,the code below will delete the 3rd line in a text file.

with open("sample.txt","r") as f:
    lines = f.readlines()
    del lines[2] 
    with open("sample.txt", "w+") as f2:
        for line in lines:
            f2.write(line)

How to delete all lines from a text file?

Glenn_ford7
  • 41
  • 1
  • 8

2 Answers2

3

Why use loop if you want to have an empty file anyways?

f = open("sample.txt", "r+") 
f.seek(0) 
f.truncate() 

This will empty the content without deleting the file!

Arju Aman
  • 412
  • 1
  • 5
  • 15
  • What is that seek() and truncate() does ? – Glenn_ford7 May 26 '21 at 12:46
  • "The seek() method sets the current file position in a file stream". Here seek(0) will move the cursor to starting point. "The truncate() method resizes the file to the given number of bytes". Since no input argument is given, it'll truncate it to 0 byte. – Arju Aman May 26 '21 at 12:50
  • you could just use `f.truncate(0)`, i used this for 3 years, worked all time. – alexzander May 26 '21 at 12:52
  • It is kinda nonsensical to open a file with `'r+'` and then immediately truncate the file. There is then nothing to read. Why not just open the file with `open("sample.txt", "w").close()` and the seek, nonsensical mode, and truncate are all unnecessary. – dawg May 26 '21 at 13:36
0

I think you to need something like this

import os

def delete_line(original_file, line_number):
    """ Delete a line from a file at the given line number """
    is_skipped = False
    current_index = 1
    dummy_file = original_file + '.bak'
    # Open original file in read only mode and dummy file in write mode
    with open(original_file, 'r') as read_obj, open(dummy_file, 'w') as write_obj:
        # Line by line copy data from original file to dummy file
        for line in read_obj:
            # If current line number matches the given line number then skip copying
            if current_index != line_number:
                write_obj.write(line)
            else:
                is_skipped = True
            current_index += 1
    # If any line is skipped then rename dummy file as original file
    if is_skipped:
        os.remove(original_file)
        os.rename(dummy_file, original_file)
    else:
        os.remove(dummy_file)
George Imerlishvili
  • 1,816
  • 2
  • 12
  • 20