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.
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 to delete a line of text file
This is in winform
. textbox1
is where you enter your word and textbox2
will display the message.
textBox2.Clear();
if (!string.IsNullOrWhiteSpace(textBox1.Text))
{
string LinesToDelete = textBox1.Text;
var Lines = File.ReadAllLines(@"E:\sample.txt");
if (Lines.Contains(textBox1.Text))
{
var newLines = Lines.Where(line => !line.Contains(LinesToDelete));
File.WriteAllLines(@"E:\sample.txt", newLines);
textBox2.Text = "Removed";
}
else
{
textBox2.Text = "Not found";
}
}
If you do not need to show the message, the code below will be sufficient.
var Lines = File.ReadAllLines(@"E:\sample.txt");
var newLines = Lines.Where(line => !line.Contains(LinesToDelete));
File.WriteAllLines(@"E:\sample.txt", newLines);
How to delete specific lines in text file?
Deleting lines cleanly and efficiently from a text file is "difficult" in the general case, but can be simple if you can constrain the problem somewhat.
Here are some questions from SO that have asked a similar question:
- How do I remove lines of data in the middle of a text file with Ruby
- Deleting a specific line in a text file?
- Deleting a line in a text file
- Delete a line of information from a text file
There are numerous others, as well.
In your case, if your input file is relatively small, you can easily afford to use the approach that you're using. Really, the only thing that would need to change to meet your criteria is to modify your input file loop and condition to this:
File.open('output.txt', 'w') do |out_file|
File.foreach('input.txt').with_index do |line,line_number|
out_file.puts line if line_number.even? # <== line numbers start at 0
end
end
The changes are to capture the line number, using the with_index
method, which can be used due to the fact that File#foreach
returns an Enumerator
when called without a block; the block now applies to with_index
, and gains the line number as a second block argument. Simply using the line number in your comparison gives you the criteria that you specified.
This approach will scale, even for somewhat large files, whereas solutions that read the entire file into memory have a fairly low upper limit on file size. With this solution, you're more constrained by available disk space and speed at which you can read/write the file; for instance, doing this to space-limited online storage may not work as well as you'd like. Writing to local disk or thumb drive, assuming that you have space available, should be no problem at all.
Delete or clear a line from a text file
You can open your file in read-write mode and delete the lines that match a condition.
with open(file_path, "r+") as fp:
lines = fp.readlines()
fp.seek(0)
for line in lines:
if "boop" not in line:
fp.write(line)
fp.truncate()
The seek
resets the file pointer.
Reference: using Python for deleting a specific line in a file
Related Topics
Go to a Specific Line in Python
Import CSV with Different Number of Columns Per Row Using Pandas
Typeerror: Unhashable Type: 'List' When Using Built-In Set Function
Python Argparse Ignore Unrecognised Arguments
In Python, How to Put a Thread to Sleep Until a Specific Time
How to Install Pip for Python 2.6
How to Install a Python Package from Within Ipython
Overwriting File in Ziparchive
Return Result from Python to Vba
Same Output in Different Workers in Multiprocessing
When Do You Use 'Self' in Python
How to Read Unicode Input and Compare Unicode Strings in Python
Weighted Choice Short and Simple