Python读取json,写入json,读取csv,写入csv

文件的读取与写入

文件的读取和写入是python很重要的部分,我还每次会忘,这次写一个博客,记录一下板子。
包含json的读取写入和csv的读取写入。
add是地址,arr是要写入的数据。

json读取

import json

def read_json(add):
    with open(add, 'rt', encoding="utf-8") as f:
        cr = json.load(f)
    f.close()
    return cr

json写入

import json

def write_json(add, arr):
    with open(add, 'a', encoding='utf-8', newline='') as f:
        json.dump(arr, f)
    f.close()
    return

csv读取

import pandas as pd

def read_csv(add):
    cr = pd.read_csv(add)
    return cr

csv写入

import csv

def write_csv(add, arr):
    with open(add, 'a', encoding='utf-8', newline='') as f:
        writer = csv.writer(f)
        writer.writerows(arr)
    f.close()

总代码

"""
    Author: Brant
    Date: 2019/9/25
"""
import json
import csv
import pandas as pd
import os
import numpy as np


def read_json(add):
    with open(add, 'rt', encoding="utf-8") as f:
        cr = json.load(f)
    f.close()
    return cr


def read_csv(add):
    cr = pd.read_csv(add)
    return cr


def write_json(add, arr):
    with open(add, 'a', encoding='utf-8', newline='') as f:
        json.dump(arr, f)
    f.close()
    return


def write_csv(add, arr):
    with open(add, 'a', encoding='utf-8', newline='') as f:
        writer = csv.writer(f)
        writer.writerows(arr)
    f.close()

你可能感兴趣的:(python)