ini文件读写

https://blog.51cto.com/hanzhichao/3201113

from configparser import ConfigParser
conf = ConfigParser()
conf.read(configFilePath, encoding=cur_encoding)
print(conf['section']['key'])


''' LutConfig.py '''
from pathlib import Path
from typing import *
import chardet
from configparser import ConfigParser

def GetDefaultConfigFilePath() -> Path:
    return Path(__file__).parent.absolute() / 'Windows/TestLutPro/Config/DefaultGame.ini'

def GetConfig(configFilePath: str) -> dict:
    # 首先二进制方式打开文件
    with open(configFilePath, 'rb') as frb:
        # 检测编码方式
        cur_encoding = chardet.detect(frb.read())['encoding']

    # 指定文件编码方式
    conf = ConfigParser()
    conf.read(configFilePath, encoding=cur_encoding)

    configResult = {}
    section = '/Script/ApplyLutTools.ApplyLutSettings'
    if conf.has_option(section, 'ServerIP'):
        configResult['ServerIP'] = conf[section]['ServerIP']
    if conf.has_option(section, 'ServerPort'):
        configResult['ServerPort'] = conf[section].getint('ServerPort')
    if conf.has_option(section, 'LocalListeningIP'):
        configResult['LocalListeningIP'] = conf[section]['LocalListeningIP']
    return configResult

def GetDefaultConfig() -> dict:
    return GetConfig(GetDefaultConfigFilePath())

自适应文件编码打开文件

import chardet
# 首先二进制方式打开文件
with open(absPath, 'rb') as frb:
    # 检测编码方式
    cur_encoding = chardet.detect(frb.read())['encoding']
# 指定文件编码方式
with open(absPath, 'r', encoding=cur_encoding) as fr:
    Content = fr.read()

文件操作

'''
w  write mode
r  read mode
a  append mode
'''
https://www.runoob.com/python/file-methods.html

# 创建文件
open('xxx.txt', 'w').close() # 经测试,不需要+号

遍历

# iterate list
for elem in lst:
    print(elem)

for idx, elem in enumerate(lst):
    print('Index: {0} element: {1}'.format(idx, elem))

for item in enumerate(lst):
    print(item) # item is tuple(index, element)


# iterate dict
for key in a_dict:
    print(key, "->", a_dict[key])

for key in a_dict.keys():
    print(key, '->', a_dict[key])

for value in a_dict.values():
    print(value)

for item in a_dict.items():
    print(item) # item is tuple(key, value)

for key, value in a_dict.items():
    print(key, '->', value)
    new_dict[value] = key