日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 编程资源 > 综合教程 >内容正文

综合教程

ioutils

發(fā)布時(shí)間:2023/12/13 综合教程 33 生活家
生活随笔 收集整理的這篇文章主要介紹了 ioutils 小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
import yaml
import json
import csv
import configparser


class IoUtils(object):

    """
    dependency:  pip install pyyaml

    yaml_r: read yaml ,return dict

    yaml_w: write yaml,data type is dict

    json_r: read json file ,return dict

    json_w: write json file ,data type is dict

    csv_r: read csv file ,return list format is:
    [
        [header],
        [column1,column2,....],
         .....
     ]

    csv_w: write data into csv file
    data format is :
        [
         [],[],
         ......
        ]
    or like this format:
        [
        (),()
        ......
        ]

    read_config: read ini file :
    return items of section or object of config or only option value


    """

    def yaml_r(self, filepath) -> dict:
        with open(filepath, 'r') as f:
            data = yaml.load(f, Loader=yaml.Loader)
        return data

    def yaml_w(self, filepath, data: dict):
        with open(filepath, 'w', encoding="utf-8") as f:
            yaml.dump(data, f)

    def json_r(self, filepath) -> dict:
        with open(filepath, 'r+')as f:
            return json.load(f)

    def json_w(self, filepath, data: dict):
        with open(filepath, "w+", encoding="utf-8")as f:
            json.dump(data, f, indent=2, ensure_ascii=False)

    def csv_r(self, csv_path) -> list:

        with open(file=csv_path, mode="r")as f:
            data = csv.reader(f, dialect='excel', delimiter=',', quotechar='|')
            data_set = [i for i in data]
        return data_set

    def csv_w(self, csv_path, data):
        with open(file=csv_path, mode='w', newline='')as f:
            wt = csv.writer(f)
            wt.writerows(data)

    def readConfig(self, filepath, section=None, option=None,
                   section_only=False, option_only=False,):
        config = configparser.ConfigParser()
        config.read(filepath)
        if section and section_only:
            return config.items(section)
        if option and option_only:
            return config.get(section=section,option=option)
        if not section_only and not option_only:
            return config

    def opens(self, filepath, mode, data=None):
        """r or w file """
        if mode == "r" or mode == "r+":
            with open(filepath, mode)as file:
                lines = file.readlines()
            return lines
        if mode == "w" or mode == "r+" and not data:
            with open(filepath, mode)as file:
                file.write(data)

  io

總結(jié)

以上是生活随笔為你收集整理的ioutils的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。

如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。