亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

實例講解python讀取各種文件的方法

 更新時間:2022年02月11日 08:43:16   作者:qq_45513965  
這篇文章主要為大家詳細介紹了python讀取各種文件的方法,,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下,希望能夠給你帶來幫助

1.yaml文件

# house.yaml--------------------------------------------------------------------------
# 1."數(shù)據(jù)結構"可以用類似大綱的"縮排"方式呈現(xiàn)
# 2.連續(xù)的項目通過減號“-”來表示,也可以用逗號來分割
# 3.key/value對用冒號“:”來分隔
# 4.數(shù)組用'[ ]'包括起來,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,"完整數(shù)據(jù)")
    """訪問特定鍵的值"""
    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.讀取的數(shù)據(jù)行末,自動加"\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[節(jié)點][key]:\t',value)
"""【第二種】獲取值"""
value = config.get('config_parameter','browser')
print('config.get(節(jié)點,key):\t',value)
"""【第三種】獲取所有值"""
value = config.items('config_parameter')
print('config.items(節(jié)點):\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.根據(jù)鍵獲取值       """
            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"\軟件包名\文件名","節(jié)點名") """
    node1 = ReadIni(r"\Ini_File\config.ini", "element")
    print(node1.get_value("class"))

總結

本篇文章就到這里了,希望能夠給你帶來幫助,也希望您能夠多多關注腳本之家的更多內容!     

相關文章

最新評論