csv、excel等文件相关操作

分享自己关于学习文件操作的相关内容。

open函数

之前一直是这样写的:

f = open('./data.txt',mode='a',encoding='utf8')
f.write("hello")
f.writelines(['xiaoming','xiaowang'])
f.write('小明与小汪')
# 文件读取
lines = f.read()
print(lines)
lines = f.readlines()
print(lines)
f.close()

这样写每次都要关闭,不是很简洁,所以我就改成了下面一种方式:

with open('./data.txt',mode='a',encoding='utf8') as f:
    # 文件写入
    f.write("helloworld123")
    f.writelines(['xiaoming','xiaowang'])
    f.write('小明与小汪')
    lines = f.read()
    lines = f.readlines()
    print(lines)

这样写每次操作完会自动关闭,也省了自己写代码关闭,也可以避免忘记关闭的烦恼,看着也更简洁。

csv 操作

写入文件:
其中的newline=’’,是新起一行的意思。

import csv

with open('./data.csv',mode='w',newline='',encoding='utf8') as file:
    # 写入文件类
    fw = csv.writer(file)
    fw.writerow(["aaaaaaa",'username'])
    fw.writerow(['helloworld','xiaoming'])

    fw.writerows([('heiheihei','wawawa'),('xiaoming','xiaowang')])

读取文件:

import csv

with open('./data.csv',mode='r',newline='',encoding='utf8') as file:
    rd = csv.reader(file)
    #一行一行的读取
    for line in rd:
        print(line)

dict方式写入数据:

import csv

with open('./data.csv',mode='w',newline='',encoding='utf8') as file:
    field_names = ['username','passwd']
     # 制定表头
    cdw = csv.DictWriter(file,fieldnames=field_names)
     # 写入表头
    cdw.writeheader()
    # 写入内容
    cdw.writerow({'username':'xiaoming','passwd':'123456'})
    cdw.writerow({'username': 'xiaowang', 'passwd': '654321'})

dict读取数据


import csv

with open('./data.csv',mode='r',newline='',encoding='utf8') as file:
    dr = csv.DictReader(file)
    for line in dr:
        print(line)

Excel文件解析

写入:

from openpyxl import Workbook

wb = Workbook()
worksheet = wb.create_sheet('data')
worksheet.append(['username','password'])
for i in range(10):
    worksheet.append([f'testuser{i}','123456'])
# 保存文件
wb.save('./data.xlsx')

读取:

from openpyxl import load_workbook
from openpyxl.worksheet.worksheet import Worksheet

wb = load_workbook('data.xlsx')
# print(wb.sheetnames)

ws:Worksheet = wb['data']
test_data = []
for row in ws.values:
    test_data.append(row)

print(test_data)

json模块

转字符串:

import  json

jstr = json.dumps(['hi',{'username':'xiaowang'}])
# 转换为字符串
print(jstr, type(jstr))
# ["hi", {"username": "xiaowang"}] <class 'str'>

with open('./data.txt',mode='w') as file:
    file.write(jstr)

解析为Python格式:

import  json

ls = json.loads('["hi", {"username": "xiaowang"}]')
print(ls,type(ls))

写入json文件:

import  json

test_data = {
    "id":1,
    "test_steps":[
        "1.打开",
        "2.输入信息"
    ]
}

with open('./data.json',mode='w',encoding='utf8') as file:
    json.dump(test_data, file)

读取json文件:

import  json
with open('./data.json',encoding='utf8') as file:
    data = json.load(file)
    print(data,type(data)) 

不得不感叹互联网上的资源是真的多,啥资源都有,真的是很不错很不错!
继续学习,继续努力,冲就对啦!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值