How to delete specific string from a file in Python?

Member

by lucile , in category: Python , 2 years ago

How to delete specific string from a file in Python?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

Member

by anthony , 2 years ago

@lucile You can use code below as example if you need to delete a specific string/line from a text file in Python:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
filename = "test.txt"

delete_string = "line 2"
lines = []
with open(filename, 'r') as file:
    for line in file:
        if line.strip() != delete_string:
            lines.append(line)

with open(filename, "w") as file:
    file.writelines(lines)


by eloy.johnston , a year ago

@lucile 

To delete a specific string from a file in Python, you can use the following approach:

  1. Open the file in read mode and store its contents in a variable.
  2. Use the replace() method to replace the string you want to delete with an empty string.
  3. Write the modified content back to the file.


Here's an example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
# Open the file in read mode
with open('file.txt', 'r') as file:
  # Read the contents of the file
  content = file.read()

# Replace the string you want to delete with an empty string
content = content.replace('string to delete', '')

# Open the file in write mode
with open('file.txt', 'w') as file:
  # Write the modified content to the file
  file.write(content)


This approach reads the entire file into memory, so it may not be suitable for very large files. In that case, you can use a different approach, such as reading and writing the file line by line, or using the mmap module to manipulate the file directly in memory.