How to Insert Lines Mid-File Using Python?

Barbara Streisand
Release: 2024-10-31 09:06:30
Original
804 people have browsed it

How to Insert Lines Mid-File Using Python?

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
Copy after login

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>
Copy after login

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
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!