Inserting a Line at the Middle of a File with Python: A Revised Perspective
Manipulating files can often involve inserting new content into specific locations. One common task is to insert a new line into the middle of a file. In this context, let's explore how to accomplish this with Python, extending the insights from a previously identified duplicate question.
Consider a text file consisting of a list of names:
Alfred Bill Donald
The goal is to insert a new name, "Charlie," at line 3 (after "Donald"). To achieve this, we can utilize Python's built-in open() function to read and write to files.
Using the with statement ensures proper file handling, opening the file in read mode ("r") to access its contents. The readlines() method returns a list of lines from the file, which we store in the variable contents.
Next, we use the insert() method to add "Charlie" at the desired line index. In this case, the line index starts from 0, so we would use contents.insert(2, "Charlie").
Finally, we reopen the file in write mode ("w") and write the modified contents back to the file. The join() method combines the lines with an empty string, ensuring a proper line-by-line format.
Here's the revised code:
<code class="python">with open("names.txt", "r") as f: contents = f.readlines() contents.insert(2, "Charlie") with open("names.txt", "w") as f: f.write("".join(contents))</code>
This code effectively inserts "Charlie" at the desired line while maintaining the original content and line breaks. Please note that the file path in the example should be modified to match the actual location of your text file.
The above is the detailed content of How to Insert a Line at the Middle of a Text File with Python?. For more information, please follow other related articles on the PHP Chinese website!