Python configparser、openpyxl模块常用方法封装

configparser

# -*- coding: utf-8 -*-


import configparser


class ConfigUtils:
    config = configparser.ConfigParser()

    def read(self, filename):
        """Read and parse a filename or an iterable of filenames."""
        self.config.read(filename, encoding="utf-8-sig")

    def get(self, _options, _section='server'):
        """Get an option value for a given section."""
        try:
            value = self.config.get(section=_section, option=_options, fallback="This section not exist this option's value.")
        except Exception as e:
            print(e)
            value = None
        return value

    def get_options_key_value(self, _section):
        """Return a list of (name, value) tuples for each option in a section."""
        return self.config.items(section=_section)

    def get_all_section(self):
        """Return a list of section names, excluding [DEFAULT]."""
        return self.config.sections()

    def get_options_by_section(self, _section):
        """Return a list of option names for the given section name."""
        return self.config.options(section=_section)

    def assert_section_in_config(self, _section):
        """assert if a section exists."""
        return _section in self.config

    def assert_options_in_section(self, _section, _options):
        """assert if a option exist in section."""
        return _options in self.config[_section]


if __name__ == '__main__':
    import os
    filename = os.path.split(os.path.realpath(__file__))[0] + './config.ini'
    configUtil = ConfigUtils()
    configUtil.read(filename=filename)
    print(configUtil.get('option1', 'PROJECT-Section1'))
    print(configUtil.get('option3', 'PROJECT-Section1'))
    print(configUtil.get_options_key_value('PROJECT-Section1'))
    print(configUtil.get_all_section())
    print(configUtil.get_options_by_section('PROJECT-Section1'))
    print(configUtil.assert_section_in_config('PROJECT-Section1'))
    print(configUtil. assert_options_in_section('PROJECT-Section1', 'Test_Type'))
    print(configUtil. assert_options_in_section('PROJECT-Section1', 'Test'))

config.ini

[PROJECT-Section1]
Test_Type = 'automation'
option1 = 'hello world'
option2 = "This is Section1's option2"

[PROJECT-Section2]
Test_Type = 'automation22222'
option1 = 'hello world222222'
option2 = "This is Section2's option2"

[PROJECT-Section3]
Test_Type = '3333333333'

openpyxl

# -*- coding: utf-8 -*-


import openpyxl


class ExcelUtils:
    workBook = None
    workSheet = None

    def load_excel(self, filename):
        """open the given filename and return the workbook."""
        try:
            self.workBook = openpyxl.load_workbook(filename)
        except BaseException as e:
            print(e)

    def get_sheet_by_name(self, name):
        """returns a worksheet by its name."""
        try:
            # !DeprecationWarning: Call to deprecated function get_sheet_by_name (Use wb[sheetname]).
            self.workSheet = self.workBook[name]
        except BaseException as e:
            print(e)

    def get_sheet_by_index(self, index=0):
        # !DeprecationWarning: Call to deprecated function get_sheet_names (Use wb.sheetnames).
        sheet_names = self.workBook.sheetnames
        print(sheet_names)
        self.workSheet = self.workBook[sheet_names[index]]
    
    def get_cell_value(self, col, row):
        """get value for specified row and column."""
        try:
            return self.workSheet.cell(column=col, row=row).value
        except BaseException as e:
            print(e)
            return None
    
    def get_cell_value_by_xy(self, str):
        """get value for coordinate, such as 'A1'."""
        try:
            return self.workSheet[str].value
        except BaseException as e:
            print(e)
            return None
    
    def get_sheet_rows(self):
        """get current sheet max row number."""
        return self.workSheet.max_row

    def get_sheet_cols(self):
        """get current sheet max column number."""
        return self.workSheet.max_column

    def write_data(self, row, col, value, path):
        """Write data to the specified rows and columns of an Excel file in the specified xlsx format."""
        try:
            self.workSheet = self.workBook.active
            self.workSheet.cell(column=col, row=row, value=value)
            self.workBook.save(path)
        except BaseException as e:
            print(e)
            return None

    def get_excel_data(self):
        """get current sheet all data, return list."""
        return tuple(self.workSheet.values)

    def get_row_value(self, row):
        """get current sheet row value, return list"""
        return self.get_excel_data()[row]

    def get_col_value(self, col='A'):
        """get current sheet column value, return list."""
        col_list = []
        for i in self.workSheet[col]:
            col_list.append(i.value)
        return col_list

    def get_row_num(self, case_id):
        """get case id row number."""
        num = 1
        col_data = self.get_col_value()
        for data in col_data:
            if case_id == data:
                return num
            num += 1
        return 0


if __name__ == '__main__':
    import os
    filename = os.path.split(os.path.realpath(__file__))[0] + '/tempdata/data.xlsx'
    excelUtils = ExcelUtils()
    excelUtils.load_excel(filename=filename)
    excelUtils.get_sheet_by_name("data")
    # excelUtils.get_sheet_by_index(index=0)
    value = excelUtils.get_cell_value(col=1, row=1)
    print(value)
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
configparser模块是一个用于读取和写入配置文件的Python标准模块。配置文件通常是用于存储应用程序的设置和配置信息的文件。下面是使用configparser模块的基本步骤: 1. 导入configparser模块: ```python import configparser ``` 2. 创建一个ConfigParser对象: ```python config = configparser.ConfigParser() ``` 3. 读取配置文件: ```python config.read('config.ini') ``` 4. 获取配置项的值: ```python value = config.get('section', 'option') ``` 其中,section是配置文件中的一个段落,option是段落中的一个选项。例如,在以下配置文件中: ``` [database] host = localhost port = 3306 user = root password = test123 database = testdb ``` 要获取host的值,可以使用以下代码: ```python host = config.get('database', 'host') print(host) # 输出:localhost ``` 5. 修改配置项的值: ```python config.set('section', 'option', 'new_value') ``` 例如,要将host修改为127.0.0.1,可以使用以下代码: ```python config.set('database', 'host', '127.0.0.1') ``` 6. 写入配置文件: ```python with open('config.ini', 'w') as f: config.write(f) ``` 完整示例: ```python import configparser config = configparser.ConfigParser() # 读取配置文件 config.read('config.ini') # 获取配置项的值 host = config.get('database', 'host') port = config.getint('database', 'port') user = config.get('database', 'user') password = config.get('database', 'password') database = config.get('database', 'database') print('host:', host) print('port:', port) print('user:', user) print('password:', password) print('database:', database) # 修改配置项的值 config.set('database', 'host', '127.0.0.1') # 写入配置文件 with open('config.ini', 'w') as f: config.write(f) ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值