How to Delete a Specific Line in a 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.

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.

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 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;

How to delete or remove a specific line from a text file

Try this code:

public static void removeLine(BufferedReader br , File f,  String Line) throws IOException{
File temp = new File("temp.txt");
BufferedWriter bw = new BufferedWriter(new FileWriter(temp));
String removeID = Line;
String currentLine;
while((currentLine = br.readLine()) != null){
String trimmedLine = currentLine.trim();
if(trimmedLine.equals(removeID)){
currentLine = "";
}
bw.write(currentLine + System.getProperty("line.separator"));

}
bw.close();
br.close();
boolean delete = f.delete();
boolean b = temp.renameTo(f);
}

PHP How to delete a specific line in a text file using user input?

Use this:

$row_number = 0;    // Number of the line we are deleting
$file_out = file("file.txt"); // Read the whole file into an array

//Delete the recorded line
unset($file_out[$row_number]);

//Recorded in a file
file_put_contents("file.txt", implode("", $file_out));


Related Topics



Leave a reply



Submit