How to Insert Lines into a File in Python Without Disrupting Existing Content?

DDD
Release: 2024-10-28 08:23:29
Original
801 people have browsed it

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

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

In this code:

  • readlines() reads the entire file into a list of lines.
  • insert() inserts "Charlie" at the specified index (line number starting from 0).
  • "".join(contents) concatenates the list of lines back into a single string.
  • write() writes the updated string back into the file.

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!

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
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!