Home > Article > Backend Development > How to Insert Lines into a File in Python Without Disrupting Existing Content?
Inserting Lines into a File in Python
Incorporating new data into a file while seamlessly adjusting the existing content can be a valuable technique. Consider a situation where you have a text file containing a list of names:
Alfred Bill Donald
Your task is to insert the name "Charlie" at a specific line (e.g., line 3) without manually shifting the remaining names down.
This can be achieved using Python's file handling capabilities:
<code class="python">with open("path_to_file", "r") as f: contents = f.readlines() contents.insert(2, "Charlie") # Index 2 represents line 3 with open("path_to_file", "w") as f: contents = "".join(contents) f.write(contents)</code>
In this code:
This method efficiently inserts lines into a file without disrupting the existing content.
The above is the detailed content of How to Insert Lines into a File in Python Without Disrupting Existing Content?. For more information, please follow other related articles on the PHP Chinese website!