ioutils

Posted sunshinekimi

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ioutils相关的知识,希望对你有一定的参考价值。

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

以上是关于ioutils的主要内容,如果未能解决你的问题,请参考以下文章

在 log.SetOutput(ioutil.Discard) 之后延迟 log.SetOutput(os.Stdout)

2022-09-24:以下go语言代码输出什么?A:1;B:3;C:13;D:7。 package main import ( “fmt“ “io/ioutil“ “net/

使用 Apache commons-io IOUtils.closeQuietly 安全吗?

IOUtils

java.io.IOException 导致的 WebView 崩溃:关闭失败:EIO(I/O 错误)libcore.io.IoUtils.close(IoUtils.java:41)

ioutil包二