当前位置:   article > 正文

python读取各种文件_python 获取文件类型

python 获取文件类型

1.yaml文件

yaml文件的特点:
1."数据结构"可以用类似大纲的"缩排"方式呈现
2.连续的项目通过减号“-”来表示,也可以用逗号来分割
3.键值对用冒号“:”来分隔
4.数组用’[ ]’括起来,hash用’{ }’来括起来
················写法 1·····················

# house.yaml--------------------------------------------------------------------------
house:
  family:
    name: Doe
    parents: John, Jane
    children:
      - Paul
      - Mark
      - Simon
address:
  number: 34
  street: Main Street
  city: Nowheretown
  zipcode: 12345
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

················写法 2·····················

family: {name: Doe,parents: [John,Jane],children: [Paul,Mark,Simone]}
address: {number: 34,street: Main Street,city: Nowheretown,zipcode: 12345}
  • 1
  • 2

文件读取

"""Read_yaml.py--------------------------------------------------------------------"""
import yaml
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))

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

2.CSV文件

269,839,558
133,632,294
870,273,311
677,823,536
880,520,889
  • 1
  • 2
  • 3
  • 4
  • 5
""" 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])

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36

3.ini文件

# config.ini--------------------------------------------------------------------
[config_parameter]
url=http://www.baidu.com
browser=FireFox

[element]
a=text
class=CSS_Selector
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
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)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
""" 读取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"))

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家小花儿/article/detail/596046
推荐阅读
相关标签
  

闽ICP备14008679号