python文件读取

导入库
pip install PyYAML==3.12
pip install pandas

yaml文件内容

test_date.yml

test_data:
- [ "M", { "code": 0, "message": "update some data!" } ]
- [ "F", { "code": 0, "message": "update some data!" } ]
- [ "X", { "code": 3333, "message": "参数格式错误" } ]
yaml文件读取

read_yaml,py

# !/usr/bin/env python
# -*-coding:utf-8 -*-

"""
# File       : read_yaml.py
# Time       :2022/9/16 19:28
# Author     :author name
# version    :python 3.7.6
# Description:
"""

import yaml
import os

print(__file__)  # G:/python_leran/InterfaceSty/ke11/read_yaml.py  系统不同反斜杠不同
# 获取真实路径(根据系统显示) os.path.realpath(__file__)

cur_path = os.path.dirname(os.path.realpath(__file__))
print(cur_path)

yaml_path = os.path.join(cur_path, "test_data.yml")
print(yaml_path)

f = open(yaml_path, "r", encoding="utf-8")
cfg = f.read()
print(cfg)

# 转python dict
d = yaml.load(cfg)
print(d)

在这里插入图片描述

yaml封装函数
# !/usr/bin/env python
# -*-coding:utf-8 -*-

"""
# File       : read_yaml.py
# Time       :2022/9/16 19:28
# Author     :author name
# version    :python 3.7.6
# Description:
"""

import yaml
import os


def read_yaml_data(yaml_path):
    f = open(yaml_path, "r", encoding="utf-8")
    cfg = f.read()
    # 转python dict
    d = yaml.load(cfg)
    return d

if __name__ == '__main__':
    cur_path = os.path.dirname(os.path.realpath(__file__))
    yaml_path = os.path.join(cur_path, "test_data.yml")
    d = read_yaml_data(yaml_path)
    print(d)
    
    #读取不同路径的ymal文件  testdata文件下test_data2.yml文件
    testdata_yaml_path = os.path.join(os.path.dirname(cur_driname),"testdata","test_data2.yml")
    d2 = read_yaml_data(testdata_yaml_path)
    print(d2)

在这里插入图片描述

json读取封装函数

test_data.json

[
    {"keyword": "Python", "expected": "Python"},
    {"keyword": "Playwright", "expected": "Playwright"}
]

read_json.py

# -*- coding: utf-8 -*-
# @Time : 2025/4/5 23:01
# @Author : write1994
# @File : read_json.py
# @Desc :

import json


def read_json_file(file_path):
    try:
        with open(file_path, 'r', encoding='utf-8') as jsonfile:
            data = json.load(jsonfile)
        return data
    except FileNotFoundError:
        print(f"文件 {file_path} 未找到")
        return None
    except json.JSONDecodeError:
        print(f"文件 {file_path} 不是有效的 JSON 格式")
        return None
    except Exception as e:
        print(f"读取 JSON 文件时出错: {e}")
        return None

if __name__ == '__main__':

    # 示例调用
    file_path = 'test_data.json'
    json_data = read_json_file(file_path)
    if json_data is not None:
        print(json_data)

csv读取封装函数

test_csv.csv

name,age,city
张三,25,北京
李四,30,上海
王五,28,广州

read_csv.py

# -*- coding: utf-8 -*-
# @Time : 2025/4/5 23:04
# @Author : write1994
# @File : read_csv.py
# @Desc :
import csv


def read_csv_file(file_path):
    data = []
    try:
        with open(file_path, 'r', encoding='utf-8') as csvfile:
            reader = csv.reader(csvfile)
            for row in reader:
                data.append(row)
        return data
    except FileNotFoundError:
        print(f"文件 {file_path} 未找到")
        return []
    except Exception as e:
        print(f"读取 CSV 文件时出错: {e}")
        return []


if __name__ == '__main__':
    # 示例调用
    file_path = 'test_csv.csv'
    csv_data = read_csv_file(file_path)
    for row in csv_data:
        print(row)

使用 pandas 库(更适合处理结构化数据,功能更强大)

pip install pandas

import pandas as pd

def read_csv_with_pandas(file_path):
    try:
        df = pd.read_csv(file_path)
        return df
    except FileNotFoundError:
        print(f"文件 {file_path} 未找到")
        return None
    except Exception as e:
        print(f"读取 CSV 文件时出错: {e}")
        return None
        
if __name__ == '__main__':
    # 示例调用
    file_path = 'test_csv.csv'
	csv_data = read_csv_with_pandas(file_path)
	if csv_data is not None:
	    print(csv_data)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值