PS:本博文仅为博主学习时,自己封装的方法,供参考。

1.读取文件:

python 文件 copy python 文件追加写入文件_写入文件


相关代码:

import os


def read_file(dire, filename):
    """
    dire:路径
    filename:文件名称,全称,带后缀
    """
    path = os.path.join(dire, filename)  # os.path为项目的根目录
    with open(path, 'r') as f:  # 以只读模式打开文件
        text = f.read()  # 读取文件
        return text


fv = read_file(r"test", "text.txt")
print(fv)

2.读取json文件,并返回字典格式:

python 文件 copy python 文件追加写入文件_读取文件_02


相关代码:

import os
import ast


def read_json_file(dire, filename):
    path = os.path.join(dire, filename)  # os.path为项目的根目录
    with open(path, 'r') as f:
        js = f.read()
        dic = ast.literal_eval(js)
        return dic


t = read_json_file(r"test", "test.json")
print(t)
print(t["zhangsan"])

3.写入文件,从第一行写入,相当于完全替换。相关代码:

import os


def write_file(dire, filename, text):
    path = os.path.join(dire, filename)
    with open(path, 'a') as f:
        f.write(text)  # 写入文件,从第一行开始


write_file(r'test', 'text.txt', "123ereew")

4.写入文件,不覆盖,换行追加,相关代码:

import os


def write_file(dire, filename, text):
    path = os.path.join(dire, filename)
    with open(path, 'a') as f:
        f.write('\n' + text)  # 写入文件,从第一行开始


write_file(r'test', 'text.txt', "4444")