python对常用文件(CSV,Excel,json,ini,yaml文件)的一些操作

open函数

文件写入:

with open('./data.txt',mode='a',encoding='utf8') as f:
    # 文件写入
    f.write("helloworld123\n")
    f.writelines(['xiaoming\n','xiaowang\n'])
f.write('张三与李四')

文件读取

with open('./data.txt',mode='r',encoding='utf8') as f:
    # 文件读取所有的内容
    # lines = f.read()
    # print(lines)
    lines = f.readlines() # 返回list 数据
    print(lines)

csv 操作

写入文件

import csv

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

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

读取文件

import csv

with open('./data.csv',mode='r',newline='',encoding='utf8') as file:
    cr = csv.reader(file)
    for line in cr:
        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': '123456'})

Excel文件解析

写入Excel文件

from openpyxl import Workbook

wb = Workbook()

worksheet = wb.create_sheet('data')

worksheet.append(['username','password'])
for i in range(100):
    worksheet.append([f'testuser{i}','123456'])

#save file
wb.save('./data.xlsx')

读取Excel文件

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(['hello',{'username':'xiaoming'}])
#转换为字符串
print(jstr, type(jstr)) # ["hello", {"username": "xiaoming"}] <class 'str'>

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

解析为Python格式

import  json

ls = json.loads('["hello", {"username": "xiaoming"}]')
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)) # {'id': 1, 'test_steps': ['1.打开浏览器', '2.输入用户信息']} <class 'dict'>

ini 文件解析

写入ini文件

import configparser
#实例化对象
config = configparser.ConfigParser()

config['Default'] = {
    "IP":"127.0.0.1",
    "port":3000,
    "user":"root",
    "passwd":123456
}

config['uat'] = {
    "IP": "192.168.1.101",
    "port": 3000,
    "user": "root",
    "passwd": 123456
}

with open('./config.ini',mode='w',encoding='utf8') as file:
    config.write(file)

[Default]
ip = 127.0.0.1
port = 3000
user = root
passwd = 123456

[uat]
ip = 192.168.1.101
port = 3000
user = root
passwd = 123456

读取ini文件

import configparser
#实例化对象
config = configparser.ConfigParser()

config.read('./config.ini')

print(config.sections())

test_data = {}
for section in config.sections():
    print(section,config[section])
    test_data[section] = {}
    for key in config[section]:
        test_data[section][key] = config[section][key]
        print(key,config[section].get(key))

print(test_data)

yaml文件

解析数据

import yaml

data = """

- Cat
- Dog
- Goldfish
"""
print(yaml.safe_load(data)) # ['Cat', 'Dog', 'Goldfish'] import yaml

data = {
    "name":'xiaoming',
    'age':20
}

print(yaml.safe_dump(data))

写入文件

import yaml

data = {
    'data':[1,2,3,4,5],
    "name":'xiaoming',
    'age':20
}
with open('./data.yaml',mode='w',encoding='utf8') as file:
yaml.safe_dump(data,file)

文件读取

import yaml

with open('./data.yaml',mode='r',encoding='utf8') as file:
    print(yaml.safe_load(file))
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值