Python操作Json、Csv、Excel文件

一、Python操作Json文件

import json

# json中使用双引号
data={
    'aa':11,
    'bb':22,
    'cc':'33'
}
# 字典转化json
print(json.dumps(data))  # 转化为json格式
# 字典写入json文件
with open('05_data.json','w') as f:
    json.dump(data,f)
# json格式转字典格式
json_data='{"ee":"11","rr":"pp","oo":22}'
print(json.loads(json_data))
# 读出json文件,读出为字典格式
with open("05_data.json",'r') as f:
    print(json.load(f))

二、Python操作Csv文件

import csv

# 读取csv
with open('test.csv','r',encoding='utf-8') as f:
    f_csv=csv.reader(f)
    next(f_csv) # 跳过第一行输出
    for line in f_csv:
        print(line)
# 写入csv
# row=[('python','3.7'),('c++','2.0'),('html','6')]
# with open("06_test.csv",'a+') as f:
#     data=csv.writer(f)
#     data.writerows(row)
# 读写字典
with open('test.csv','r') as f:
    f_read=csv.DictReader(f)
    for i in f_read:
        print(i)
# 写入字典
header=['A','B','C']
rows=[{'A':'a','B':'b','C':'c'},
      {'A':'1','B':'2','C':'3'},
      {'A':'5','B':'6','C':'7'}]
with open('06_dict.csv','a+') as f:
    f_csv=csv.DictWriter(f,header)
    f_csv.writeheader() # 写入标题
    f_csv.writerows(rows)

三、Python操作Excel文件

import xlwt # 写入Excel
import xlrd # 读取Excel

def create():
    # 创建Excel
    Excel_book=xlwt.Workbook()
    # 创建一个sheet
    sheet=Excel_book.add_sheet('test01')
    # 在第一行第一列写入文字‘Python’
    # sheet.write(0,0,'Python')
    t=1
    for i in range(3):
        for j in range(3):
            sheet.write(i,j,t)
            t+=1
    Excel_book.save('07_test.xlsx')
def get_data():
    data=xlrd.open_workbook('07_test.xlsx')
    # 获取第一个sheet
    sheet=data.sheets()[0]
    # 获取行数和列数
    rows=sheet.nrows # 行
    cols=sheet.ncols # 列
    # 获取行数据
    for i in range(rows):
        print(sheet.row_values(i))
    # 获取列数据
    for j in range(cols):
        print(sheet.col_values(j))
    # 获取指定单元格数据
    print(sheet.cell_value(0,0))
if __name__ == '__main__':
    create()
    get_data()

猜你喜欢

转载自blog.csdn.net/KK_2018/article/details/113099475