首頁 > 軟體

範例講解python讀取各種檔案的方法

2022-02-11 10:03:30

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_Filedata.csv")
    for i in range(3):
        print(csv.read_line(1)[i])
    csv1 = Read_CSV(r"CSV_Filerandom_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_Fileconfig.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_Fileconfig.ini", "element")
    print(node1.get_value("class"))

總結

本篇文章就到這裡了,希望能夠給你帶來幫助,也希望您能夠多多關注it145.com的更多內容!     


IT145.com E-mail:sddin#qq.com