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

目录

  • 1.yaml文件
  • 2.CSV文件
  • 3.ini文件
  • 总结

1.yaml文件
# house.yaml--------------------------------------------------------------------------# 1."数据结构"可以用类似大纲的"缩排"方式呈现# 2.连续的项目通过减号“-”来表示,也可以用逗号来分割# 3.key/value对用冒号“:”来分隔# 4.数组用'[ ]'包括起来,hash用'{ }'来包括# ················写法 1·····················house:family:name: Doeparents: John, Janechildren:- Paul- Mark- Simonaddress:number: 34street: Main Streetcity: Nowheretownzipcode: 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,jsonwith 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,558133,632,294870,273,311677,823,536880,520,889

""" CSV文件读取 """""" 1.with语句自动关闭文件2.文件读取的方法read()读取全部返回字符串readline()读取一行返回字符串readlines() 读取全部返回列表(按行)3.读取的数据行末,自动加"\n""""import osclass Read_CSV(object):def __init__(self, csv_path):self.csv_path = csv_pathdef read_line(self, line_number):try:"""【CSV文件的路径】"""csv_file_path = os.path.dirname(os.path.dirname(__file__)) + self.csv_pathwith open(csv_file_path, "r") as f1:""" |读取某一行内容|--->|去掉行末"\n"|--->|以","分割字符串| """line1 = f1.readlines()[line_number - 1]line1 = line1.strip("\n")list1 = line1.split(",")return list1except 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.combrowser=FireFox[element]a=textclass=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 = https://www.it610.com/article/config['config_parameter']['url']print('config[节点][key]:\t',value)"""【第二种】获取值"""value = https://www.it610.com/article/config.get('config_parameter','browser')print('config.get(节点,key):\t',value)"""【第三种】获取所有值"""value = https://www.it610.com/article/config.items('config_parameter')print('config.items(节点):\t',value)

""" 读取ini文件 """import configparserimport osclass ReadIni(object):def __init__(self, file_path, node):self.node = nodeself.file_path = file_pathdef 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_pathconfig.read(path1)value = https://www.it610.com/article/config.get(self.node, key)return valueexcept 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"))


总结 【实例讲解python读取各种文件的方法】本篇文章就到这里了,希望能够给你带来帮助,也希望您能够多多关注脚本之家的更多内容!

    推荐阅读