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

Linda Hamilton
Release: 2024-11-02 03:58:02
Original
179 people have browsed it

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

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

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!

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!