Search and replace a line in a file in Python

Search and replace a line in a file in Python

To search and replace a specific line in a file in Python, you can read the contents of the file, make the necessary changes, and then write the updated contents back to the file. Here's a step-by-step guide:

Suppose you have a text file named "example.txt" with the following content:

Line 1 Line 2 Line 3 Line 4 

You want to replace "Line 3" with "New Line 3".

Here's how you can do it:

# Define the file path file_path = "example.txt" # Read the file into a list of lines with open(file_path, 'r') as file: lines = file.readlines() # Search for the line to replace search_line = "Line 3\n" replacement_line = "New Line 3\n" for i, line in enumerate(lines): if line == search_line: lines[i] = replacement_line # Write the updated lines back to the file with open(file_path, 'w') as file: file.writelines(lines) 

After running this code, the contents of "example.txt" will be updated as follows:

Line 1 Line 2 New Line 3 Line 4 

Here's a breakdown of the code:

  1. We define the file_path variable to store the path to the file you want to modify.

  2. We use a with statement to open the file in read mode ('r') and read its contents into a list of lines using readlines().

  3. We specify the line you want to search for (search_line) and the replacement line (replacement_line).

  4. We loop through the list of lines and replace the line if it matches the search_line.

  5. Finally, we open the file in write mode ('w') and write the updated lines back to the file using writelines().

This code allows you to search for and replace a specific line in a text file while preserving the rest of the file's content.

Examples

  1. How to Search and Replace a Line in a File in Python

    • Description: This query explores how to search for a specific line in a text file and replace it with a new line.
    • Code:
      file_path = 'example.txt' target_line = 'Old text' new_line = 'New text' # Read the file content with open(file_path, 'r') as file: lines = file.readlines() # Search for the target line and replace it updated_lines = [new_line if line.strip() == target_line else line for line in lines] # Write the updated content back to the file with open(file_path, 'w') as file: file.writelines(updated_lines) 
  2. Using Line Numbers to Search and Replace in a File

    • Description: This query discusses how to search and replace a specific line in a file using its line number.
    • Code:
      file_path = 'example.txt' line_number = 3 # Line number to replace (1-based) new_line = 'Replacement text\n' # New text with newline # Read the file content with open(file_path, 'r') as file: lines = file.readlines() # Replace the specified line lines[line_number - 1] = new_line # Adjust for 0-based index # Write the updated content back to the file with open(file_path, 'w') as file: file.writelines(lines) 
  3. Search and Replace a Line in a File Based on a Substring

    • Description: This query explores how to search for a specific substring within lines of a text file and replace the whole line.
    • Code:
      file_path = 'example.txt' substring = 'target' # Substring to search for new_line = 'Replaced line with target\n' # New line to replace the old one # Read the file content with open(file_path, 'r') as file: lines = file.readlines() # Search and replace lines containing the substring updated_lines = [new_line if substring in line else line for line in lines] # Write the updated content back to the file with open(file_path, 'w') as file: file.writelines(updated_lines) 
  4. Search and Replace a Line in a File with Regex

    • Description: This query discusses how to use regular expressions to search and replace a line in a text file in Python.
    • Code:
      import re file_path = 'example.txt' regex_pattern = r'^Old.*' # Regex pattern to find lines starting with 'Old' replacement = 'This is the new text\n' # Read the file content with open(file_path, 'r') as file: lines = file.readlines() # Use regex to find and replace matching lines updated_lines = [replacement if re.match(regex_pattern, line) else line for line in lines] # Write the updated content back to the file with open(file_path, 'w') as file: file.writelines(updated_lines) 
  5. Search and Replace Multiple Lines in a File in Python

    • Description: This query discusses how to search and replace multiple lines in a file, allowing for bulk updates.
    • Code:
      file_path = 'example.txt' replacements = { 'Line 1 text': 'Updated text for line 1\n', 'Line 2 text': 'Updated text for line 2\n' } # Read the file content with open(file_path, 'r') as file: lines = file.readlines() # Replace multiple lines based on the dictionary of replacements updated_lines = [replacements.get(line.strip(), line) for line in lines] # Write the updated content back to the file with open(file_path, 'w') as file: file.writelines(updated_lines) 
  6. Search and Replace a Line in a Large File Efficiently

    • Description: This query discusses how to efficiently search and replace a line in a large file without loading the entire content into memory.
    • Code:
      import tempfile file_path = 'large_file.txt' target_line = 'Old line' new_line = 'New replacement line\n' # Create a temporary file to store the modified content with tempfile.NamedTemporaryFile(delete=False) as temp_file: # Read the original file and write to the temporary file with open(file_path, 'r') as file: for line in file: if line.strip() == target_line: temp_file.write(new_line.encode()) else: temp_file.write(line.encode()) # Replace the original file with the temporary file import os os.replace(temp_file.name, file_path) # Overwrite the original file with the temporary file 
  7. Appending to a File After Replacing a Line

    • Description: This query explores how to replace a line in a file and then append additional content to the end of the file.
    • Code:
      file_path = 'example.txt' target_line = 'Old text' new_line = 'Replaced text\n' additional_content = '\nAdditional content to be appended' # Read the file and replace the target line with open(file_path, 'r') as file: lines = file.readlines() updated_lines = [new_line if line.strip() == target_line else line for line in lines] # Write the updated content and then append additional content with open(file_path, 'w') as file: file.writelines(updated_lines) file.write(additional_content) # Append content at the end 
  8. Replacing a Line in a File with User Input

    • Description: This query discusses how to replace a specific line in a file based on user input, allowing interactive updates.
    • Code:
      file_path = 'example.txt' target_line = 'Original text' # Ask user for new content new_line = input('Enter new text for the line: ') + '\n' # Replace the target line with user-provided content with open(file_path, 'r') as file: lines = file.readlines() updated_lines = [new_line if line.strip() == target_line else line for line in lines] with open(file_path, 'w') as file: file.writelines(updated_lines) 
  9. Search and Replace a Line in a File with Specific Condition

    • Description: This query discusses how to replace a line in a file based on a specific condition, such as the presence of a keyword.
    • Code:
      file_path = 'example.txt' keyword = 'keyword_to_find' new_line = 'New line with replacement\n' # Search and replace lines containing the keyword with open(file_path, 'r') as file: lines = file.readlines() updated_lines = [new_line if keyword in line else line for line in lines] with open(file_path, 'w') as file: file.writelines(updated_lines) 
  10. Search and Replace a Line in a File and Write to a New File


More Tags

isnull inotifypropertychanged http-status-code-406 microsoft-teams dotfiles i3 loading ienumerable oracle12c kubernetes-ingress

More Python Questions

More Math Calculators

More Physical chemistry Calculators

More Pregnancy Calculators

More Electronics Circuits Calculators