give me a code for python to insert text in a line of ellection
- User
give me a code for python to insert text in a line of ellection
- Assistant
If you want to insert text into a specific line of a text file in Python, you can read the entire file, modify the desired line, and then write the results back to the file. Here's a simple example demonstrating this process:
def insert_text_in_line(file_path, line_number, text_to_insert): """Inserts text at a specific line in the file.""" try: # Read the existing lines from the file with open(file_path, 'r') as file: lines = file.readlines() # Check if the line number is within the valid range if line_number < 1 or line_number > len(lines) + 1: print(f"Error: Line number {line_number} is out of range.") return # Insert the new text at the specified line lines.insert(line_number - 1, text_to_insert + '\n') # Write the modified lines back to the file with open(file_path, 'w') as file: file.writelines(lines) print(f"Text inserted at line {line_number}.") except FileNotFoundError: print(f"Error: The file '{file_path}' was not found.") except Exception as e: print(f"An error occurred: {e}") # Example usage insert_text_in_line('your_file.txt', 3, 'This is the new text to insert.')