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

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

Linda Hamilton
Linda HamiltonOriginal
2024-11-02 10:50:30400browse

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

Inplace Prepending to the Beginning of a File

When attempting to append a line to the start of a file using the append mode ('a'), users may encounter an undesired writing at the file's end due to the file pointer automatically advancing to the end.

To overcome this limitation and truly prepend a line to the file's beginning, several methods can be employed:

Method 1: Reading and Rewriting the File

If loading the entire file into memory is feasible, the following function can be used:

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

This approach loads the file's contents into the variable content, allowing the line to be prepended and the modified content to be rewritten to the beginning of the file.

Method 2: Using the File Input Module

An alternative approach involves using the fileinput module:

<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,
        else:
            print xline,</code>

This method iterates over the file's lines, and when encountering the first line, preprends the specified line to it before printing both lines.

The exact mechanism of this method is not entirely clear, but it allows for inplace editing of the file without the need to load the entire contents into memory, potentially making it suitable for larger files.

The above is the detailed content of How to Prepend 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