广告
返回顶部
首页 > 资讯 > 后端开发 > Python >实例讲解python读取各种文件的方法
  • 555
分享到

实例讲解python读取各种文件的方法

2024-04-02 19:04:59 555人浏览 泡泡鱼

Python 官方文档:入门教程 => 点击学习

摘要

目录1.yaml文件2.CSV文件3.ini文件总结1.yaml文件 # house.yaml--------------------------------------------

1.yaml文件

# house.yaml--------------------------------------------------------------------------
# 1."数据结构"可以用类似大纲的"缩排"方式呈现
# 2.连续的项目通过减号“-”来表示,也可以用逗号来分割
# 3.key/value对用冒号“:”来分隔
# 4.数组用'[ ]'包括起来,hash用'{ }'来包括
# ················写法 1·····················
house:
  family:
    name: Doe
    parents: John, Jane
    children:
      - Paul
      - Mark
      - Simon
address:
  number: 34
  street: Main Street
  city: Nowheretown
  zipcode: 12345
# ················写法 2·····················
#family: {name: Doe,parents:[John,Jane],children:[Paul,Mark,Simone]}
#address: {number: 34,street: Main Street,city: Nowheretown,zipcode: 12345}
"""Read_yaml.py--------------------------------------------------------------------"""
import yaml,JSON
with open("house.yaml",mode="r",encoding="utf-8") as f1:
    res = yaml.load(f1,Loader=yaml.FullLoader)
    print(res,"完整数据")
    """访问特定键的值"""
    print("访问特定键的值",res['house']['family']['parents'])
    print(type(res))
    """字典转换为json"""
    transition_json = json.dumps(res)
    print(transition_json)
    print(type(transition_json))

2.CSV文件

269,839,558
133,632,294
870,273,311
677,823,536
880,520,889
""" CSV文件读取 """
""" 1.with语句自动关闭文件
    2.文件读取的方法
    read()      读取全部    返回字符串
    readline()  读取一行    返回字符串  
    readlines() 读取全部    返回列表(按行)
    3.读取的数据行末,自动加"\n"       """
import os
class Read_CSV(object):
    def __init__(self, csv_path):
        self.csv_path = csv_path
    def read_line(self, line_number):
        try:
            """【CSV文件的路径】"""
            csv_file_path = os.path.dirname(os.path.dirname(__file__)) + self.csv_path
            with open(csv_file_path, "r") as f1:
                """ |读取某一行内容|--->|去掉行末"\n"|--->|以","分割字符串| """
                line1 = f1.readlines()[line_number - 1]
                line1 = line1.strip("\n")
                list1 = line1.split(",")
                return list1
        except Exception as e:
            print(f"!!! 读取失败,因为 {e}")

if __name__ == '__main__':
    """example = Read_CSV(r"\软件包名\文件名") """
    csv = Read_CSV(r"\CSV_File\data.csv")
    for i in range(3):
        print(csv.read_line(1)[i])
    csv1 = Read_CSV(r"\CSV_File\random_list.csv")
    for i in range(3):
        print(csv1.read_line(3)[i])

3.ini文件

# config.ini--------------------------------------------------------------------
[config_parameter]
url=Http://train.atstudy.com
browser=FireFox
[element]
a=text
class=CSS_Selector
import configparser;import os
""" 1.调用【configparser】模块"""
config = configparser.ConfigParser();print(f"config类型  {type(config)}")
""" 2.ini文件的路径"""
path1 = os.path.dirname(os.path.dirname(__file__))+r"\Ini_File\config.ini"
print(f"ini文件的路径  {path1}")
""" 3.读取ini文件"""
config.read(path1);print(f"config.read(path1)  {config.read(path1)}")
"""【第一种】获取值"""
value = config['config_parameter']['url']
print('config[节点][key]:\t',value)
"""【第二种】获取值"""
value = config.get('config_parameter','browser')
print('config.get(节点,key):\t',value)
"""【第三种】获取所有值"""
value = config.items('config_parameter')
print('config.items(节点):\t',value)
""" 读取ini文件 """
import configparser
import os
class ReadIni(object):
    def __init__(self, file_path, node):
        self.node = node
        self.file_path = file_path
    def get_value(self, key):
        try:
            """ 1.调用【configparser】模块--->2.ini文件的路径
                3.读取ini文件--->4.根据键获取值       """
            config = configparser.ConfigParser()
            path1 = os.path.dirname(os.path.dirname(__file__)) + self.file_path
            config.read(path1)
            value = config.get(self.node, key)
            return value
        except Exception as e:
            print(f"!!! 读取失败,因为 {e}")

if __name__ == '__main__':
    """example = ReadIni(r"\软件包名\文件名","节点名") """
    node1 = ReadIni(r"\Ini_File\config.ini", "element")
    print(node1.get_value("class"))

总结

本篇文章就到这里了,希望能够给你带来帮助,也希望您能够多多关注编程网的更多内容!     

--结束END--

本文标题: 实例讲解python读取各种文件的方法

本文链接: https://www.lsjlt.com/news/138778.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作