Delete Specific Line from a Text File

How to delete a specific line in a file?

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.

Python program to delete a specific line in a text file

Your problem is that lines[5] will always be equal to line6. You never modified the sixth line in lines, so line6 and lines[5] are still equal. Thus, the condition lines[5] != line6 will always fail.

If you want to always remove the sixth line from your file, you can use enumerate. For example:

with open("file.txt", "r") as infile:
lines = infile.readlines()

with open("file.txt", "w") as outfile:
for pos, line in enumerate(lines):
if pos != 5:
outfile.write(line)

How can I delete a specific line from a txt file based on user input?

def remove():
delete_value = input("Enter the value you wish to delete: ")

with open("value.txt", "r") as f:
file = f.readlines()
with open("value.txt", "w") as f:
for line in file:
# we will skip the line that contains our target word
# in this case the delete_animal
words = line.strip("\n").lower().split(' ')
if delete_value.lower() not in words:
f.write(line)

Input file:

line 1
line 2
line 3
line 4
may name is sudipto
my name is sudiptoandiloveprogramming

user input: sudipto

Output file after delete:

line 1
line 2
line 3
line 4
my name is sudiptoandiloveprogramming

Delete specific line from a text file?

If the line you want to delete is based on the content of the line:

string line = null;
string line_to_delete = "the line i want to delete";

using (StreamReader reader = new StreamReader("C:\\input")) {
using (StreamWriter writer = new StreamWriter("C:\\output")) {
while ((line = reader.ReadLine()) != null) {
if (String.Compare(line, line_to_delete) == 0)
continue;

writer.WriteLine(line);
}
}
}

Or if it is based on line number:

string line = null;
int line_number = 0;
int line_to_delete = 12;

using (StreamReader reader = new StreamReader("C:\\input")) {
using (StreamWriter writer = new StreamWriter("C:\\output")) {
while ((line = reader.ReadLine()) != null) {
line_number++;

if (line_number == line_to_delete)
continue;

writer.WriteLine(line);
}
}
}

Delete and replace a Specific Line in .txt file

Here is a working example of what you want to do: it increments the number of likes for a movie. It does not store the contents of the whole file into the buffer. The file might be of a large size, so it might not be very efficient.

#include <fstream>
#include <iostream>
#include <string>

int main()
{
std::fstream fileMovies{"sample.txt",
std::ios_base::in | std::ios_base::out | std::ios_base::binary};
if (!fileMovies.is_open())
{
std::cerr << "Failed to open file" << std::endl;
return -1;
}

std::string movieName{};
std::getline(std::cin, movieName);

std::string line{};
line.reserve(256);

long long int pos = fileMovies.tellp();
for (line; std::getline(fileMovies, line);)
{
if (line.find(movieName) != std::string::npos)
break;
line.clear();
pos = fileMovies.tellp();
}

if (fileMovies.eof())
{
std::cerr << "Failed to find the movie by name" << std::endl;
return -1;
}

long long int curPos = fileMovies.tellp();

// TODO: check format
long long int commaPos = line.rfind(',');
fileMovies.seekp(pos + commaPos + 2);

int liked = 0;
fileMovies >> liked;
fileMovies.seekp(pos + commaPos + 2);
fileMovies << ++liked;

return 0;
}

Output:

PS C:\dev\builds\editfile\Release-Visual Studio\bin> cat .\sample.txt
SNO, Name, NoOfPeopleLiked
1, The Shawshank Redemption, 77
2, The Godfather, 20
3, Into The Wild, 35
4, The Dark Knight, 55
5, 12 Angry Men, 44
6, Schindler's List, 33
7, The Lord of the Rings: The Return of the King, 25
8, Pulp Fiction, 23
9, The Good, the Bad and the Ugly, 32
10, The Lord of the Rings: The Fellowship of the Ring, 56
PS C:\dev\builds\editfile\Release-Visual Studio\bin> .\main.exe
Angry
PS C:\dev\builds\editfile\Release-Visual Studio\bin> cat .\sample.txt
SNO, Name, NoOfPeopleLiked
1, The Shawshank Redemption, 77
2, The Godfather, 20
3, Into The Wild, 35
4, The Dark Knight, 55
5, 12 Angry Men, 45
6, Schindler's List, 33
7, The Lord of the Rings: The Return of the King, 25
8, Pulp Fiction, 23
9, The Good, the Bad and the Ugly, 32
10, The Lord of the Rings: The Fellowship of the Ring, 56

Keep in mind, that you can't append new characters in the middle of the file (nor can you erase them). You can only overwrite the existing ones at the current position.
So in order for this to work properly, you should use the number of likes with trailing spaces, or in format like 0045.
Also, pay attention that you have to use std::fstream with flags in | out | binary. Binary is necessary in order to properly count the current position.

Delete specific line number(s) from a text file using sed?

If you want to delete lines from 5 through 10 and line 12th:

sed -e '5,10d;12d' file

This will print the results to the screen. If you want to save the results to the same file:

sed -i.bak -e '5,10d;12d' file

This will store the unmodified file as file.bak, and delete the given lines.

Note: Line numbers start at 1. The first line of the file is 1, not 0.

How to delete from a text file, all lines that contain a specific string?

To remove the line and print the output to standard out:

sed '/pattern to match/d' ./infile

To directly modify the file – does not work with BSD sed:

sed -i '/pattern to match/d' ./infile

Same, but for BSD sed (Mac OS X and FreeBSD) – does not work with GNU sed:

sed -i '' '/pattern to match/d' ./infile

To directly modify the file (and create a backup) – works with BSD and GNU sed:

sed -i.bak '/pattern to match/d' ./infile

Delete specific line from text file

Why is not the line removed?

https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html

  • E remove(int index) Removes the element at the specified position in this list.
  • boolean remove(Object o) Removes the first occurrence of the specified element from this list, if it is present.

Since Integer line is Object and not a primitive data type int, this call

filecontent.remove(line);

tries to remove the line with a content equal to new Integer(1).

Change the method argument to int line or add type cast to the call filecontent.remove((int) line).

Why is an empty line added?

The extra space is added by this statement:

String textToAppend = "\r\n" + filecontent.get(i);

Change it like this:

String textToAppend = filecontent.get(i) + "\r\n";

How to delete a specific line in a text file in c++

Currently you delete only the first occurrence of deleteline in each line. To delete the whole line starting with deleteline you have to replace

line.replace(line.find(deleteline), deleteline.length(), "");
temp << line << endl;

with

std::string id(line.begin(), line.begin() + line.find(" "));
if (id != deleteline)
temp << line << endl;


Related Topics



Leave a reply



Submit