How to delete a specific line in a file?

PythonFileInput

Python Problem Overview


Let's say I have a text file full of nicknames. How can I delete a specific nickname from this file, using Python?

Python Solutions


Solution 1 - Python

First, open the file and get all your lines from the file. Then reopen the file in write mode and write your lines back, except for the line you want to delete:

with open("yourfile.txt", "r") as f:
    lines = f.readlines()
with open("yourfile.txt", "w") as f:
    for line in lines:
        if line.strip("\n") != "nickname_to_delete":
            f.write(line)

You need to strip("\n") the newline character in the comparison because if your file doesn't end with a newline character the very last line won't either.

Solution 2 - Python

Solution to this problem with only a single open:

with open("target.txt", "r+") as f:
    d = f.readlines()
    f.seek(0)
    for i in d:
        if i != "line you want to remove...":
            f.write(i)
    f.truncate()

This solution opens the file in r/w mode ("r+") and makes use of seek to reset the f-pointer then truncate to remove everything after the last write.

Solution 3 - Python

The best and fastest option, rather than storing everything in a list and re-opening the file to write it, is in my opinion to re-write the file elsewhere.

with open("yourfile.txt", "r") as file_input:
    with open("newfile.txt", "w") as output: 
        for line in file_input:
            if line.strip("\n") != "nickname_to_delete":
                output.write(line)

That's it! In one loop and one only you can do the same thing. It will be much faster.

Solution 4 - Python

This is a "fork" from @Lother's answer (which I believe that should be considered the right answer).


For a file like this:

$ cat file.txt 
1: october rust
2: november rain
3: december snow

This fork from Lother's solution works fine:

#!/usr/bin/python3.4

with open("file.txt","r+") as f:
    new_f = f.readlines()
    f.seek(0)
    for line in new_f:
        if "snow" not in line:
            f.write(line)
    f.truncate()

Improvements:

  • with open, which discard the usage of f.close()
  • more clearer if/else for evaluating if string is not present in the current line

Solution 5 - Python

The issue with reading lines in first pass and making changes (deleting specific lines) in the second pass is that if you file sizes are huge, you will run out of RAM. Instead, a better approach is to read lines, one by one, and write them into a separate file, eliminating the ones you don't need. I have run this approach with files as big as 12-50 GB, and the RAM usage remains almost constant. Only CPU cycles show processing in progress.

Solution 6 - Python

I liked the fileinput approach as explained in this answer: Deleting a line from a text file (python)

Say for example I have a file which has empty lines in it and I want to remove empty lines, here's how I solved it:

import fileinput
import sys
for line_number, line in enumerate(fileinput.input('file1.txt', inplace=1)):
    if len(line) > 1:
            sys.stdout.write(line)

> Note: The empty lines in my case had length 1

Solution 7 - Python

If you use Linux, you can try the following approach.
Suppose you have a text file named animal.txt:

$ cat animal.txt  
dog
pig
cat 
monkey         
elephant  

Delete the first line:

>>> import subprocess
>>> subprocess.call(['sed','-i','/.*dog.*/d','animal.txt']) 

then

$ cat animal.txt
pig
cat
monkey
elephant
  

Solution 8 - Python

Probably, you already got a correct answer, but here is mine. Instead of using a list to collect unfiltered data (what readlines() method does), I use two files. One is for hold a main data, and the second is for filtering the data when you delete a specific string. Here is a code:

main_file = open('data_base.txt').read()    # your main dataBase file
filter_file = open('filter_base.txt', 'w')
filter_file.write(main_file)
filter_file.close()
main_file = open('data_base.txt', 'w')
for line in open('filter_base'):
    if 'your data to delete' not in line:    # remove a specific string
        main_file.write(line)                # put all strings back to your db except deleted
    else: pass
main_file.close()

Hope you will find this useful! :)

Solution 9 - Python

I think if you read the file into a list, then do the you can iterate over the list to look for the nickname you want to get rid of. You can do it much efficiently without creating additional files, but you'll have to write the result back to the source file.

Here's how I might do this:

import, os, csv # and other imports you need
nicknames_to_delete = ['Nick', 'Stephen', 'Mark']

I'm assuming nicknames.csv contains data like:

Nick
Maria
James
Chris
Mario
Stephen
Isabella
Ahmed
Julia
Mark
...

Then load the file into the list:

 nicknames = None
 with open("nicknames.csv") as sourceFile:
     nicknames = sourceFile.read().splitlines()

Next, iterate over to list to match your inputs to delete:

for nick in nicknames_to_delete:
     try:
	     if nick in nicknames:
		     nicknames.pop(nicknames.index(nick))
         else:
             print(nick + " is not found in the file")
     except ValueError:
	     pass

Lastly, write the result back to file:

with open("nicknames.csv", "a") as nicknamesFile:
    nicknamesFile.seek(0)
    nicknamesFile.truncate()
    nicknamesWriter = csv.writer(nicknamesFile)
    for name in nicknames:
        nicknamesWriter.writeRow([str(name)])
nicknamesFile.close()

Solution 10 - Python

In general, you can't; you have to write the whole file again (at least from the point of change to the end).

In some specific cases you can do better than this -

if all your data elements are the same length and in no specific order, and you know the offset of the one you want to get rid of, you could copy the last item over the one to be deleted and truncate the file before the last item;

or you could just overwrite the data chunk with a 'this is bad data, skip it' value or keep a 'this item has been deleted' flag in your saved data elements such that you can mark it deleted without otherwise modifying the file.

This is probably overkill for short documents (anything under 100 KB?).

Solution 11 - Python

I like this method using fileinput and the 'inplace' method:

import fileinput
for line in fileinput.input(fname, inplace =1):
    line = line.strip()
    if not 'UnwantedWord' in line:
        print(line)

It's a little less wordy than the other answers and is fast enough for

Solution 12 - Python

Save the file lines in a list, then remove of the list the line you want to delete and write the remain lines to a new file

with open("file_name.txt", "r") as f:
    lines = f.readlines() 
    lines.remove("Line you want to delete\n")
    with open("new_file.txt", "w") as new_f:
        for line in lines:        
            new_f.write(line)

Solution 13 - Python

here's some other method to remove a/some line(s) from a file:

src_file = zzzz.txt
f = open(src_file, "r")
contents = f.readlines()
f.close()

contents.pop(idx) # remove the line item from list, by line number, starts from 0

f = open(src_file, "w")
contents = "".join(contents)
f.write(contents)
f.close()

Solution 14 - Python

> You can use the re library

Assuming that you are able to load your full txt-file. You then define a list of unwanted nicknames and then substitute them with an empty string "".

# Delete unwanted characters
import re

# Read, then decode for py2 compat.
path_to_file = 'data/nicknames.txt'
text = open(path_to_file, 'rb').read().decode(encoding='utf-8')

# Define unwanted nicknames and substitute them
unwanted_nickname_list = ['SourDough']
text = re.sub("|".join(unwanted_nickname_list), "", text)

Solution 15 - Python

Do you want to remove a specific line from file so use this snippet short and simple code you can easily remove any line with sentence or prefix(Symbol).

with open("file_name.txt", "r") as f:
lines = f.readlines() 
with open("new_file.txt", "w") as new_f:
    for line in lines:
        if not line.startswith("write any sentence or symbol to remove line"):
            new_f.write(line)

Solution 16 - Python

To delete a specific line of a file by its line number:

Replace variables filename and line_to_delete with the name of your file and the line number you want to delete.

filename = 'foo.txt'
line_to_delete = 3
initial_line = 1
file_lines = {}

with open(filename) as f:
    content = f.readlines() 

for line in content:
    file_lines[initial_line] = line.strip()
    initial_line += 1

f = open(filename, "w")
for line_number, line_content in file_lines.items():
    if line_number != line_to_delete:
        f.write('{}\n'.format(line_content))

f.close()
print('Deleted line: {}'.format(line_to_delete))

Example output:

Deleted line: 3

Solution 17 - Python

Take the contents of the file, split it by newline into a tuple. Then, access your tuple's line number, join your result tuple, and overwrite to the file.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSourDView Question on Stackoverflow
Solution 1 - PythonhoubysoftView Answer on Stackoverflow
Solution 2 - PythonLotherView Answer on Stackoverflow
Solution 3 - PythonBarnabeView Answer on Stackoverflow
Solution 4 - PythonivanleonczView Answer on Stackoverflow
Solution 5 - PythonKingzView Answer on Stackoverflow
Solution 6 - PythonDeepView Answer on Stackoverflow
Solution 7 - PythonRenView Answer on Stackoverflow
Solution 8 - Pythonandrii1986View Answer on Stackoverflow
Solution 9 - PythonA MalikView Answer on Stackoverflow
Solution 10 - PythonHugh BothwellView Answer on Stackoverflow
Solution 11 - PythonRu887321View Answer on Stackoverflow
Solution 12 - PythonHenrique AndradeView Answer on Stackoverflow
Solution 13 - PythonungalcrysView Answer on Stackoverflow
Solution 14 - PythonmrkView Answer on Stackoverflow
Solution 15 - PythonSidd501View Answer on Stackoverflow
Solution 16 - PythonAram MaliachiView Answer on Stackoverflow
Solution 17 - PythonNikhilView Answer on Stackoverflow