Python之文件操作笔记(json/csv/excel/yaml)

14 阅读2分钟

一,python对json文件的操作

import json
# 数据驱动之对json的操作

#读取json,load是读文件,loads是读字符串
def readjson():
    with open('b.json', 'r', encoding="utf-8") as f:
        data=json.load(f)
    print(data)
    print(data[0])

# 增加数据 在末尾追加一条,先读后写
def addjson(new_item):
    with open('b.json', 'r', encoding="utf-8") as f:
        data=json.load(f)
        data.append(new_item)

    with open('b.json', 'w', encoding="utf-8") as f:
        json.dump(data,f,ensure_ascii=False,indent=4)

# 修改数据 先读后改
def updatajson(index,new_item):
    with open('b.json', 'r', encoding="utf-8") as f:
        data=json.load(f)

    if 0<=index<len(data):
        data[index]=new_item

    with open('b.json', 'w', encoding="utf-8") as f:
        json.dump(data,f,ensure_ascii=False,indent=4)

# 删除某一列,先读后写
def deljson(index):
    with open('b.json', 'r', encoding="utf-8") as f:
        data=json.load(f)

    if 0<=index<len(data):
        del data[index]

    with open('b.json', 'w', encoding="utf-8") as f:
        json.dump(data,f,ensure_ascii=False,indent=4)

二,python对csv文件操作

import csv
# 数据驱动之对csv的操作
# 读csv数据
def readcsv():
    rows=[]
    with open("a.csv", "r+", encoding="utf-8", ) as f:
        read=csv.DictReader(f)
        for row in read:
            rows.append(row)
    return print(rows)

# 追加
# 传字符串会被分开,只能传列表
def addcsv(row):
    with open("a.csv", "a+", encoding="utf-8", newline="") as f:
        writer=csv.writer(f)
        writer.writerow(row)

# 修改,先改再写回去
def updatecsv(index,new_row):
    with open("a.csv", "r+", encoding="utf-8", newline="") as f:
        data=list(csv.DictReader(f))
        data[index]={
            "name":new_row[0],
            "age":new_row[1]
        }
    with open("a.csv", "w+", encoding="utf-8", newline="") as f:
        headers=["name","age"]
        writer=csv.DictWriter(f,headers)
        writer.writeheader()
        writer.writerows(data)

# 删除内容 先删除再将内容写进去
def delcsv(index):
    with open("a.csv", "r+", encoding="utf-8", newline="") as f:
        data=list(csv.DictReader(f))

        if 0<=index<len(data):
            del data[index]

    with open("a.csv", "w+", encoding="utf-8", newline="") as f:
        headers=["name","age"]
        writer=csv.DictWriter(f,headers)
        writer.writeheader()
        writer.writerows(data)

三,python对excel文件操作

def readexcel(file_name):
    df = pd.read_excel(file_name,engine='openpyxl')
    # 按照每一行转化为字典
    return df.to_dict('records')

# 追加一行数据
def addexcel(new_item):
    # 读取原来的文件
    df = pd.read_excel(file_name,engine='openpyxl')
    # 把新数据转化成表格
    df_new=pd.DataFrame(new_item)
    # 合并新老数据
    df_all=pd.concat([df,df_new],ignore_index=True)
    # 写回文件
    df_all.to_excel(file_name,index=False,engine='openpyxl')

# 修改某一行的数据
def updataexcel(rows_index,new_item):
    df = pd.read_excel(file_name,engine='openpyxl')

    # 定位到 【指定行号,指定字段】 把值改进去
    for key,value in new_item.items():
        df.loc[rows_index,key]=value
    # 写回
    df.to_excel(file_name,index=False,engine='openpyxl')

# 删除某一行的数据
def delexcel(rows_index):
    df = pd.read_excel(file_name,engine='openpyxl')
    df=df.drop(rows_index)
    df.to_excel(file_name,index=False,engine='openpyxl')

四,python对yaml文件操作

import yaml
def readyaml():
    with open("d.yaml", 'r') as f:
        data = yaml.safe_load(f)
        print(data)

# 追加数据
def addyaml(new_item):
    with open("d.yaml", 'r') as f:
        data = yaml.safe_load(f)

        if data is None:
            data = []

        data.append(new_item)
    with open("d.yaml", 'w') as f:
        yaml.dump(data, f, allow_unicode=True, sort_keys=False, indent=2)

# 修改数据
def updata(index,new_item):
    with open("d.yaml", 'r') as f:
        data = yaml.safe_load(f)

        for key in new_item:
            data[index][key] = new_item[key]

    with open("d.yaml", 'w') as f:
        yaml.dump(data, f, allow_unicode=True, sort_keys=False, indent=2)

# 删除数据
def delyaml(index):
    with open("d.yaml", 'r') as f:
        data = yaml.safe_load(f)

        del data[index]

    with open("d.yaml", 'w') as f:
        yaml.dump(data, f, allow_unicode=True, sort_keys=False, indent=2)