Removing of Specific Line in 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.

Remove a specific letter from a specific line in a file in python

You can read the file line by line and identify the line you want to modify. Then identify the index/location of the character you want to modify(remove).
Replace it with blank and write the text line by line into the file.

#opeing the .txt file
fp = open("data.txt", "r")
#reading text line by line
text= fp.readlines()
#searching for character to remove
char = text[1][-2]
#removing the character by replacing it with blank
text[1] = text[1].replace(char, "")

#opeing the file in write mode
fw = open("data.txt", "w")
#writing lines one by one
for lines in text:
fw.write(lines)
#closing the file
fw.close()

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.

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)

Remove specific line in text file

There are two problems with what you're doing:

  • you are comparing the whole line to the input with "equals" .... for
    that to match, the user couldn't not just enter "cats", they'd need
    to enter "cats, 20, 30" since that is what a line contains.
  • even if it did match, you're still writing "line" to the output file

You can fix it like this:

 while((line = reader.readLine()) != null) {
String trimmedLine = line.trim();
if(!trimmedLine.startsWith(removedLine)) {

writer.write(line +
System.getProperty("line.separator"));
}
}

This will only write the line if it does not start with the input.

As a side-note, you should look at using the "try with resources" statement to open your reader/writer to ensure things get cleaned up properly even in the event of an exception.

How do I remove a specific line from a text file in python

Your code is mostly correct insofar that it'll correctly remove the \n characters from your lines.

You also have an indentation issue with telling the user that the book has been removed, but that could be an issue with how you posted the code in your question here. It doesn't affect how your code tests each line.

However, removing the \n characters from each book value doesn't mean that the string read from the file will match the string the user typed:

  • Your lines could have extra whitespace. That's harder to see when you open your book file in a text editor, but you can test this by using a little bit more Python code.

    Try using either the repr() function or the ascii() function to print the line, which will make them look as if they are Python string literals. If you are only using English text, the difference between ascii and repr() doesn't really matter; what's important is that you get to see the string value in a way that makes it easier to spot things like spaces.

    Just add a print("The value of book is:", ascii(book)) and perhaps print("The value of book_to_delete is:", ascii(book_to_delete)) to your loop:

    with open('listOfBook.txt', 'w') as list_of_books:
    for book in books:
    print("The value of book is:", ascii(book))
    print("The value of book_to_delete is:", ascii(book_to_delete))
    if book.strip('\n') != book_to_delete:

    You could remove the "\n" argument from str.strip() and remove all whitespace characters from start and end to solve this:

    if book.strip() != book_to_delete.strip():

    You can play with the function in a Python interactive session:

    >>> book = "The Great Gatsby   \n"
    >>> book
    'The Great Gatsby \n'
    >>> print(book.strip("\n"))
    The Great Gatsby
    >>> print(ascii(book.strip("\n")))
    'The Great Gatsby '
    >>> print(ascii(book.strip()))
    'The Great Gatsby'

    Notice how print(book.strip("\n")) doesn't really show you that there are extra spaces there, but print(ascii(book.strip("\n"))) shows, by the location of the '...' quoting, that the string is longer. Finally, using str.strip() with no arguments removed those extra spaces.

    Also, note that the user could also be adding extra spaces, do remove those too.

  • The user could be using a different mix of uppercase and lowercase characters. You could use the str.casefold() function` on both values to make sure that differences in casing are ignored:

    if book.strip().casefold() != book_to_delete.casefold():

Your code, as posted, has an indentation issue. The lines

print(book_to_delete, 'had been removed from the library data base')
input('Please press enter to go back to staff menu')

are currently indented to fall under the if book.strip('\n') != book_to_delete: test block, so they are executed each time a book value from your file is tested and found to be a different book.

You want to remove enough indentation so that only is indented once past the level of def delete_book():, so still part of the function, but not part of any other block:

def delete_book():
book_to_delete = input('Please input the name of the book that will be removed from the library: ')
with open("listOfBook.txt", "r") as list_of_books:
books = list_of_books.readlines()
with open('listOfBook.txt', 'w') as list_of_books:
for book in books:
if book.strip() != book_to_delete.strip():
list_of_books.write(book)
print(book_to_delete, 'had been removed from the library data base')
input('Please press enter to go back to staff menu')

That way it is only executed after you have written all lines that don't match book_to_delete to the file, and the file has been closed. Note that in the above example, I also changed .strip("\n") into .strip() and added an extra strip() call to the user input too..

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/string from a text file (fstream/c++)

Let's think about the structure of your program:

while(getline(database, line)){
if(line.find(find) != string::npos) {
var = line;
cout << line << endl;
string choice{};
cout << "Is this the line you want to delete[y/n]: ";
cin >> choice;

if (choice =="y")
{
while(getline(database, line)){
if(line != var){
outputFile << line << endl;
}
}
database.close();
outputFile.close();
remove("database");
rename("outputFileName","database");
} else {
continue;
}
}
}

Think about what you're going to do. You've asked for the text of the line to delete. You're now reading lines.

You read line 1. Let's say it doesn't match. You continue. You don't write line one.

You read line 2. It matches, but let's say they say No when you ask to verify? You continue, but you don't write anything to your output file.

This continues until you say Yes. At that point, you copy the remaining lines -- but you've ignored the ones you skipped.

I think what you need to do is output non-matching lines to your output file.



Related Topics



Leave a reply



Submit