Hướng dẫn how to append a line at the beginning of a file in python - cách nối một dòng vào đầu tệp trong python

Trong các chế độ

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,
3 hoặc
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,
4, bất kỳ văn bản nào được thực hiện ở cuối tệp, ngay cả khi vào thời điểm hiện tại khi hàm
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,
5 được kích hoạt trước khi viết. Bạn có thể làm những gì bạn muốn trong hai cách cư xử.

Có thể sử dụng theo cách đầu tiên nếu không có vấn đề gì để tải tệp vào bộ nhớ:, can be used if there are no issues to load the file into memory:

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)

Cách thứ 2::

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,

Tôi không biết phương pháp này hoạt động như thế nào dưới mui xe và nếu nó có thể được sử dụng trên tệp lớn. Đối số 1 được chuyển đến đầu vào là những gì cho phép viết lại một dòng tại chỗ; Các dòng sau phải được di chuyển về phía trước hoặc lùi lại để hoạt động tại chỗ diễn ra, nhưng tôi không biết cơ chế

Trong bài viết này, chúng tôi sẽ thảo luận về cách chèn một hoặc nhiều dòng ở đầu văn bản hoặc tệp CSV trong Python.

Không có cách trực tiếp để chèn văn bản ở giữa một tệp. Do đó, chúng tôi phải tạo một tệp mới với dòng mới ở đầu và sau đó đổi tên tệp này thành tệp gốc. Chúng tôi đã tạo một chức năng cho điều đó,

import os


def prepend_line(file_name, line):
    """ Insert given string as a new line at the beginning of a file """
    # define name of temporary dummy file
    dummy_file = file_name + '.bak'
    # open original file in read mode and dummy file in write mode
    with open(file_name, 'r') as read_obj, open(dummy_file, 'w') as write_obj:
        # Write given line to the dummy file
        write_obj.write(line + '\n')
        # Read lines from original file one by one and append them to the dummy file
        for line in read_obj:
            write_obj.write(line)
    # remove original file
    os.remove(file_name)
    # Rename dummy file as the original file
    os.rename(dummy_file, file_name)

Chức năng này làm gì?

  • Nó chấp nhận một đường dẫn tệp và đường thẳng được chèn làm đối số
  • Tạo và mở một tệp tạm thời ở chế độ ghi.
  • Thêm dòng đã cho làm dòng đầu tiên trong tệp tạm thời
  • Mở tệp gốc ở chế độ đọc và đọc nội dung của dòng tệp từng dòng
    • Đối với mỗi dòng, hãy nối vào tệp tạm thời
  • Xóa tệp gốc.
  • Đổi tên tệp tạm thời là tệp gốc.

Hãy để sử dụng chức năng này để chèn một dòng ở đầu tệp.

Giả sử chúng ta có một tệp ‘sample.txt, và nội dung của nó là,

Hello this is a sample file
It contains sample text
Dummy Line A
Dummy Line B
Dummy Line C
This is the end of file

Bây giờ thêm một dòng mới ‘Đây là dòng đầu tiên ở đầu tệp,

# Insert a line before the first line of a file 'sample.txt'
prepend_line("sample.txt", "This is a first line")

Bây giờ nội dung của tệp là,

This is a first line
Hello this is a sample file
It contains sample text
Dummy Line A
Dummy Line B
Dummy Line C
This is the end of file

Một dòng mới được thêm vào đầu tệp.

Quảng cáo

Chèn nhiều dòng vào đầu tệp

Giả sử chúng ta có một danh sách các chuỗi,

list_of_lines = ['Another line to prepend', 'Second Line to prepend',  'Third Line to prepend']

Chúng tôi muốn thêm từng chuỗi trong danh sách dưới dạng dòng mới trong tệp.

Để chèn nhiều dòng vào đầu tệp, chúng ta có thể gọi hàm đã tạo ở trên predend_line () nhiều lần khác nhau, tức là một lần cho mỗi dòng như thế này,

[ prepend_line("sample.txt", line) for line in list_of_lines ]

Nhưng đó không phải là một giải pháp hiệu quả vì nó sẽ mở, đóng và chuyển nội dung vào một tệp tạm thời cho mỗi chuỗi/dòng trong danh sách. Vì vậy, hãy để Lôi tạo một hàm chỉ mở tệp một lần và cũng chèn nhiều dòng ở đầu tệp, tức là.

import os

def prepend_multiple_lines(file_name, list_of_lines):
    """Insert given list of strings as a new lines at the beginning of a file"""

    # define name of temporary dummy file
    dummy_file = file_name + '.bak'
    # open given original file in read mode and dummy file in write mode
    with open(file_name, 'r') as read_obj, open(dummy_file, 'w') as write_obj:
        # Iterate over the given list of strings and write them to dummy file as lines
        for line in list_of_lines:
            write_obj.write(line + '\n')
        # Read lines from original file one by one and append them to the dummy file
        for line in read_obj:
            write_obj.write(line)

    # remove original file
    os.remove(file_name)
    # Rename dummy file as the original file
    os.rename(dummy_file, file_name)

Hàm này chấp nhận một tên tệp và danh sách các chuỗi là đối số. Sau đó thêm các chuỗi trong danh sách dưới dạng Newlines trong một tệp tạm thời và sau đó nối các dòng từ tệp gốc vào tệp tạm thời. Cuối cùng, đổi tên tệp tạm thời thành tệp gốc.

Hãy để sử dụng chức năng này,

Nội dung của tệp ‘mẫu.txt, là,

This is a first line
Hello this is a sample file
It contains sample text
Dummy Line A
Dummy Line B
Dummy Line C
This is the end of file

Chèn chuỗi vào danh sách dưới dạng các dòng mới ở đầu tệp ‘sample.txt,

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

Bây giờ nội dung của tệp ‘sample.txt, là,

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

Ví dụ hoàn chỉnh như sau,

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