Home >Backend Development >Python Tutorial >How Can I Insert a Line into a File at a Specific Position Using Python?
Inserting a Line at the Middle of a File in Python
Inserting a line at a specified position in a file while maintaining the integrity of the existing content can be achieved using Python's file handling capabilities.
To insert a line at index x in a file, follow these steps:
Here's an example code that implements these steps:
<code class="python">with open("path_to_file", "r") as f: contents = f.readlines() # Insert the line at index x index = 2 value = "Charlie" contents.insert(index, value) with open("path_to_file", "w") as f: contents = "".join(contents) f.write(contents)</code>
This code opens the file, reads its contents into a list contents, inserts the line "Charlie" at line 2 (index 1), then overwrites the file with the modified content.
The above is the detailed content of How Can I Insert a Line into a File at a Specific Position Using Python?. For more information, please follow other related articles on the PHP Chinese website!