python:从文件头部写入数据

以下示例的功能是每次执行代码,都将当前时间写入到文件的头部

核心代码

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

代码示例

# -*- 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()

可以看到,输出的文件内容每次都是从头部写入的

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

参考文章

  1. 如何利用Python在一个文件的头部插入数据

猜你喜欢

转载自blog.csdn.net/mouday/article/details/131722225
今日推荐