zoukankan      html  css  js  c++  java
  • 一些常用的文本文件格式(TXT,JSON,CSV)以及如何从这些文件中读取和写入数据

    TXT文件

    txt是微软在操作系统上附带的一种文本格式,文件以.txt为后缀。

    从txt文件中读取数据:

    with open ('xxx.txt') as file:
        data=file.readlines()

    将数据写入txt文件:

    with open ('xxx.txt','a',encoding='utf-8') as file:
        file.write('xxxx')

    注:a表示append,将数据一行行写入文件


    JSON文件

    JSON指JavaScript对象表示法(JavaScript Object Notation),是一种轻量级的数据交换格式,易于人阅读和编写,同时也易于机器解析和生成,文件以.json为后缀。

    JSON对象可以以字符串的形式储存在文件中(不一定是json文件)。

    一些常见的JSON格式:

    {"key1":"value1","key2":"value2"}   由多个key:value键值对组成
    {"key":["a","b","sojson.com"]}      value是一个array的JSON格式

    (注:JSON格式数据必须用双引号,错误的JSON格式:{'name':'imooc'})

    读取以JSON格式储存的数据文件(JSON格式的数据被储存在其他格式的文件里):

    1)使用json模块(首先import json)

    with open ('xxx') as file:
        data=json.loads(file.read())

    从json文件中读取数据:

    1)使用json模块(首先import json)

    with open ('xxx.json') as file:
        data=json.load(file)

    2)使用pandas库(首先import pandas as pd)

    data=pd.read_json(file_name,orient)

    将数据写入json文件:

    1)使用json模块(首先import json)

    with open ('xxx.json','w') as file:
        file.write(json.dumps("xxxx"))

    如数据内有中文:

    with open ('xxx.json','w',encoding='utf-8') as file:
        file.write(json.dumps("xxxx",ensure_ascii=False))

    注:json库的loads()方法将JSON格式的文本字符串转为JSON对象

           json库的load()方法直接读取json文件

           json库的dumps()方法将JSON对象转为文本字符串


    CSV文件

    CSV是一种通用的、相对简单的文件格式,称为逗号分隔值(Comma-Separated Values),有时也称为字符分隔值,因为分隔字符也可以不是逗号,文件以.csv为后缀。

    从csv文件中读取数据:

    1)使用csv模块(首先import csv)

    with open ('xxx.csv',encoding='utf-8') as file:
        data=csv.reader(file,delimiter=',')

    2)使用pandas库(首先import pandas as pd)

    data=pd.read_csv(file_name,sep=',')

    将数据写入csv文件:

    1)使用csv模块(首先import csv)

    with open('xxx.csv','w') as file:
        writer=csv.writer(file)
        writer.writerow([xxxx])

    2)使用pandas库(首先import pandas as pd)

    data.to_csv(file_name,encoding='utf-8')
  • 相关阅读:
    API文档大集合
    jenkins 构建 job 并获取其状态的实现
    jenkins 插件乱码处理与文件上传
    更优雅的配置:docker/运维/业务中的环境变量
    部署仓库中 nginx 下游依赖配置改进
    dotnet core 在 MIPS64 下的移值进度:EA 版本已经发布
    tmux 编译安装过程
    各数据源的时间/日期的提取能力对比
    关于若干性能指标的阐述
    为缓存、外部接口调用添加超时处理
  • 原文地址:https://www.cnblogs.com/HuZihu/p/11176658.html
Copyright © 2011-2022 走看看