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. 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
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
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;
withstd::string id(line.begin(), line.begin() + line.find(" "));
if (id != deleteline)
temp << line << endl;
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 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);
}
}
}
Related Topics
Warning While Installing The Rails Plugin
When Is The Enumerator::Yielder#Yield Method Useful
Problems While Making a Generic Model in Ruby on Rails 3
Filtering Sensitive Data with Vcr
Obtaining Number of Block Parameters
How to Stub/Mock a Call to The Command Line with Rspec
Clean Install Osx 10.9.1 Returns "Undefined Method 'Path2Class'" When Trying to Install Gems
Mongodb Server Doesn't Start at Gitlab Runner Using Gitlab-Ci
Rails on Netbeans: Uncaught Exception: No Such File to Load - Script/Server or Script/Console
Actionmailer Pass Local Variables to The Erb Template
How to Interact with a Caldav Server from Ruby
How to Share Code Across Chef Cookbooks in a Chef-Repo
How to Set in a Middleware a Variable Accessible in All My Application
Recommended Way to Generate a Presigned Url to S3 Bucket in Ruby