Home  >  Article  >  Backend Development  >  How to Add a Line to the Beginning of a File in Python?

How to Add a Line to the Beginning of a File in Python?

Linda Hamilton
Linda HamiltonOriginal
2024-11-02 03:58:02169browse

How to Add a Line to the Beginning of a File in Python?

How to Add a Line to the Beginning of a File

Suppose you want to add a line to the beginning of a file, but using the standard append mode in Python, the line is appended to the end of the file. How can you achieve this?

Implementation

There are two ways to accomplish this:

1st Way (Memory Intensive):

<code class="python">def line_prepender(filename, line):
    with open(filename, 'r+') as f:
        content = f.read()
        f.seek(0, 0)
        f.write(line.rstrip('\r\n') + '\n' + content)</code>

In this method, the entire file is read into memory, line is added to the beginning, and then the modified content is overwritten back into the file.

2nd Way (Streaming):

<code class="python">def line_pre_adder(filename, line_to_prepend):
    f = fileinput.input(filename, inplace=1)
    for xline in f:
        if f.isfirstline():
            print(line_to_prepend.rstrip('\r\n') + '\n' + xline, end='')
        else:
            print(xline, end='')</code>

This method streams the file line by line, overwriting the original file. It uses the fileinput module to iterate through the lines and inserts the given line at the beginning of the first line.

The choice of method depends on the file size and available memory. The 2nd way is preferred for large files to avoid memory issues.

The above is the detailed content of How to Add a Line to the Beginning of a File in Python?. 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