Inserting Lines Mid-File with Python
Inserting a line at the middle of a file with Python is possible through a few different methods. One approach is to use the readlines() function to read the file's contents into a list. This list can then be edited by inserting the desired line at the specified index. Once the edits are made, the contents of the list can be written back to the file using the writelines() function.
For example, consider a file containing a list of names:
Alfred Bill Donald
To insert the name "Charlie" at line 3, we can use the following code:
<code class="python">with open("names.txt", "r") as f: contents = f.readlines() contents.insert(3, "Charlie\n") with open("names.txt", "w") as f: contents = "".join(contents) f.write(contents)</code>
This code opens the file "names.txt" for reading, reads its contents into the list contents, inserts "Charlie" at line 3, and then opens the file for writing. The contents of the list are joined into a string and written back to the file.
After running this code, the file "names.txt" will contain the following:
Alfred Bill Charlie Donald
The line "Charlie" has been successfully inserted at line 3, shifting all subsequent lines down one line.
The above is the detailed content of How to Insert Lines Mid-File Using Python?. For more information, please follow other related articles on the PHP Chinese website!