python: write data from file header

The function of the following example is to write the current time to the head of the file every time the code is executed

core code

with open(filename, "r+") as f:
    old = f.read()
    f.seek(0)
    f.write(content)
    f.write(old)

code example

# -*- coding: utf-8 -*-
"""
@File    : demo.py
@Date    : 2023-07-14
"""
import os
from datetime import datetime


def write_to_file_head(filename, content):
    """
    将内容写入到文件头部
    :param filename: 文件名,不存在会创建
    :param content: 写入的内容
    :return:
    """
    # 如果不存在,会报错:
    # IOError: [Errno 2] No such file or directory
    if os.path.exists(filename):
        with open(filename, "r+") as f:
            old = f.read()
            f.seek(0)
            f.write(content)
            f.write(old)
    else:
        with open(filename, "w") as f:
            f.write(content)


def main():
    filename = 'demo.txt'

    data = datetime.now().strftime("%Y-%m-%d %H:%M:%S")

    write_to_file_head(filename, data + os.linesep)


if __name__ == '__main__':
    main()

It can be seen that the output file content is written from the head every time

demo.txt

2023-07-14 14:02:11
2023-07-14 14:02:10
2023-07-14 14:02:09
2023-07-14 14:02:08
2023-07-14 14:02:06
2023-07-14 14:02:05
2023-07-14 14:02:04
2023-07-14 14:02:00

reference article

  1. How to use Python to insert data at the head of a file

Guess you like

Origin blog.csdn.net/mouday/article/details/131722225