Home  >  Article  >  Backend Development  >  How to Insert Lines into a File in Python Without Disrupting Existing Content?

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

DDD
DDDOriginal
2024-10-28 08:23:29792browse

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:

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

Statement:
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