脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - 实例讲解python读取各种文件的方法

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

2022-09-21 11:09qq_45513965 Python

这篇文章主要为大家详细介绍了python读取各种文件的方法,,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下,希望能够给你带来帮助

1.yaml文件

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# 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}
?
1
2
3
4
5
6
7
8
9
10
11
12
"""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文件

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

?
1
2
3
4
5
6
7
# config.ini--------------------------------------------------------------------
[config_parameter]
url=http://train.atstudy.com
browser=FireFox
[element]
a=text
class=CSS_Selector
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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
21
22
23
""" 读取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"))

总结

本篇文章就到这里了,希望能够给你带来帮助,也希望您能够多多关注服务器之家的更多内容!     

原文链接:https://blog.csdn.net/qq_45513965/article/details/122871290

延伸 · 阅读

精彩推荐