python(24)-json-csv-读写

json和csv是常用的数据文件格式。常用的就是读写。open ,read,write,close。

1.json文件的读写
2.CSV文件的读写
3.两种文件格式判断与转换
4.OS文件系统操作函数
分离文件名和后缀,用以判断文件类型os.path.splitext

with open(filepath,mode="r",encoding="utf-8") as f:   #f 为文件
取代  f=open(filepath,mode="r",encoding="utf-8") 
with 时 不需要f.close()

导入包
import csv
import json
import os

1.json文件的读写
 

"""
json
     f=open(filepath,mode="r",encoding="utf-8")
     file_list=json.load(f)                         #读     内容    file_list
     json.dump(top5_list,f,ensure_ascii=False)      #写入   内容    top5_list
     
"""


2.CSV文件的读写

"""

csv  读写文件
       reader =csv.reader(f)
       for line in reader: 
       
     writer=csv.writer(f)                                    
     for line in lines:
        writer.writerow(line)

"""


3.OS文件系统操作
 

文件操作
  f=open(filepath,mode="r",encoding="utf-8")
  f.close()
此处 用 
withopen 操作文件,结束后不用close()

OS 文件操作
os.remove()   删除文件
os.makedirs() 创建多层目录
os.rmdir()    删除单级目录
os.rename()   重命令文件
os.path.isfile() 是否为文件
os.path.isdir()  是否为目录
os.path.join()   连接目录
os.path.splitext() 文件分割为文件名和扩展名 tmp .txt

4.实例

def jointest():
    l1 = ['1', '2', '3', '4']
    print('+'.join(l1))
    """
    输出
    1+2+3+4
    不可以写成l1=[1,2,3,4] 要写成字符而不是数组
    """

def process_json(filepath):                               #读取json
    with open(filepath,mode="r",encoding="utf-8") as f:   # with open 不用f.close()
        content_list=json.load(f)                         # 读取文件内容
    print(content_list)

def process_csv(filepath):
    with open(filepath,mode="r",encoding="utf-8",newline="") as f: #区别在于 newline=""
        reader=csv.reader(f)                                       #读取CSV
        for row in reader:
            print(",".join(row))                                    #字符串加“,”输出

#csv->json
def  file_csv_json():
    filepath="myinput.json"                                    #分解 文件名 名+后缀
    filename,file_ext=os.path.splitext(filepath)               #通过后缀判断文件类型 os好用的一个函数
    if file_ext=='.json':
        process_json(filepath)
    elif file_ext=='.csv':
        process_csv(filepath)
    else:
        print("不支持的文件格式")

    with open("myout.csv")  as somefile:
        for line in somefile:
            print(line)

def  file_csv(file_list):                                   #写CSV
    lines=[]
    lines.append(list(file_list[0].keys()))                 #列名
    for city in file_list:
        lines.append(list(city.value()))
    f=open('myout.csv',"w",encoding='utf-8',newline='')     #打开文件
    writer=csv.writer(f)                                    #写入
    for line in lines:                                      #每行写入 line
        writer.writerow(line)
    f.close()


def file_json():              #读写json
    filepath="./myin.json"
    f=open(filepath,mode="r",encoding="utf-8")           #打开文件
    file_list=json.load(f)                               #下载
    file_list.sort(key=lambda city:city['aqi'])          #
    top5_list=file_list[:5]
    f=open("top5_aqi.json",mode="w",encoding="utf-8")    #文件
    json.dump(top5_list,f,ensure_ascii=False)            #写入的内容top5_list
    f.close()

def main():       #程序入口,放入你想要实现的函数
    file_json()
  #  file_csv()
  #  file_csv_json()
    pass

if __name__=="__main__":
    main()

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值