Home >Backend Development >Python Tutorial >How to Replace a Specific Line in a Text File Using Python?
Editing a Specific Line in a Text File in Python
In this scenario, you have a text file with multiple lines and you want to replace a specific line with a new value. While the provided Python code attempts to modify a line, it's incorrect. Here's a more efficient approach:
# Open the file for reading with open('stats.txt', 'r') as file: # Read the file into a list of lines data = file.readlines() # Print the data to verify its current state print(data) # Get the specific line you want to modify line_to_edit = 1 # Index starts from 0 # Replace the old line with the new value data[line_to_edit] = 'Mage\n' # Add a newline character at the end # Open the file for writing and overwrite the contents with open('stats.txt', 'w') as file: # Write the updated data back to the file file.writelines(data)
This approach uses the readlines() function to read all the lines into a list. Then, you can directly access the desired line by its index (remembering that indexing starts from 0). Once the specific line is modified, the entire list is written back to the file using writelines().
This method is efficient because it reads the entire file into memory, allowing you to freely modify and overwrite specific lines. Unlike the original code, it doesn't attempt to overwrite individual lines directly, which could lead to incorrect results.
The above is the detailed content of How to Replace a Specific Line in a Text File Using Python?. For more information, please follow other related articles on the PHP Chinese website!