python代码碎片

python代码碎片


1.接口调用

main.py

from query_hbase.tools import Worker
import logging

logging.basicConfig(level=logging.DEBUG,
                    format='%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s',
                    filename="log.txt",
                    filemode="a")  # 模式同文件


def main():
    """
    调用接口入口函数
    :param args:
    :param kwargs:
    :return:
    """
    # 程序开关
    activate = True
    # 循环计数器
    cnt = 1
    while activate:
        """循环主体"""
        print("* * " * 15 + " exit 请输入 1 " + "* * " * 15)  # 退出提醒
        if cnt == 1:  # 授权码和查询参数只需要输入一次

            # 请输入授权码
            csrf_token = input("请输入授权码: ")
            logging.info("授权码为:%s" % csrf_token)

            if csrf_token == '1':  # 退出使用
            	logging.info("退出")
                print("* * " * 15 + " 谢谢使用!!! " + "* * " * 15)
                return

            # 请输入查询码
            query_code = input("请输入查询码: ")
            logging.info("查询码为:%s" % query_code)

        # 请输入查询参数
        query_params = input("请输入查询参数: ")
        logging.info("查询参数为:%s" % query_params)
        if query_params == '1':  # 退出使用
        	logging.info("退出")
            print("* * " * 15 + " 谢谢使用!!! " + "* * " * 15)
            return

        worker = Worker(url='http://www.baidu.com')
        results = worker.call_api(csrf_token=csrf_token, query_code=query_code, query_params=query_params)
        logging.info("查询结果为:%s" % results)
        cnt += 1


if __name__ == '__main__':
    main()


tools.py

import requests
import json
import random


class Worker(object):
    """
    工具类
    """

    def __init__(self, url=None, **kwargs):
        self.url = url
        self.kwargs = kwargs

    def call_api(self, *args, **kwargs):
        params = {'csrf_token': kwargs.get('csrf_token'), 'query_code': kwargs.get('query_code'),
                  'query_params': kwargs.get('query_params')}
        results = requests.get(self.url, json=params).content
        print(params, results, '%d06' % (random.randint(0, 100000),), sep='\n')
        return results
        
    def __str__(self):
        return "这是一个工具类!!!"

2.删除非空目录

import os


def custem_rmdir(path):
    """
    删除非空文件夹
    :param path: 文件夹路径
    :return: None
    """
    # 判断是文件夹是否为空
    if len(os.listdir(path)):
        # 遍历其中的内容 将这些内容全部删除
        for sub_name in os.listdir(path):
            # print(sub_name)
            # 判断是文件还是文件夹
            sub_path = os.path.join(path, sub_name)
            if os.path.isfile(sub_path):  # 是文件就删除
                os.remove(sub_path)
            else:  # 是文件夹, 就递归
                custem_rmdir(sub_path)

    os.rmdir(path)
3…在桌面生成文件夹或者删除
import os
import sys

# 获取 桌面路径
desk = os.path.join(os.path.expanduser('~'), "Desktop") + "/"

# 文件路径
file_path = desk + "WYH_DIR"


def custem_rmdir(path):
    """
    删除非空文件夹
    :param path: 文件夹路径
    :return: None
    """
    # 判断是文件夹是否为空
    if len(os.listdir(path)):
        # 遍历其中的内容 将这些内容全部删除
        for sub_name in os.listdir(path):
            # print(sub_name)
            # 判断是文件还是文件夹
            sub_path = os.path.join(path, sub_name)
            if os.path.isfile(sub_path):  # 是文件就删除
                os.remove(sub_path)
            else:  # 是文件夹, 就递归
                custem_rmdir(sub_path)

    os.rmdir(path)


if __name__ == '__main__':
    if os.path.exists(file_path):
        custem_rmdir(file_path)
    else:
        os.mkdir(file_path)

4工具类
import os
import sys
import xlrd
import xlwt
import xlutils.copy


class Worker(object):
    """工具类"""

    def __init__(self):
        """初始化"""
        self.desk_path = os.path.join(os.path.expanduser('~'), "Desktop")

    def __str__(self):
        """返回对象信息(must string)"""
        str_data = "这是一个工具类!!!"
        return str_data

    def rmdir(self, path):
        """
        删除非空文件夹
        :param path: 文件夹路径
        :return: None
        """
        # 判断是文件夹是否为空
        if len(os.listdir(path)):
            # 遍历其中的内容 将这些内容全部删除
            for sub_name in os.listdir(path):
                # print(sub_name)
                # 判断是文件还是文件夹
                sub_path = os.path.join(path, sub_name)
                if os.path.isfile(sub_path):  # 是文件就删除
                    os.remove(sub_path)
                else:  # 是文件夹, 就递归
                    self.rmdir(sub_path)

        os.rmdir(path)

    def search_folder(self, path):
        """遍历搜索文件夹"""
        data = []
        # 判断是文件夹是否为空
        if len(os.listdir(path)):
            # 遍历其中的内容 将这些内容全部删除
            for sub_name in os.listdir(path):
                # print(sub_name)
                # 判断是文件还是文件夹
                sub_path = os.path.join(path, sub_name)
                if os.path.isfile(sub_path):  # 是文件做处理

                    # 调用文件处理函数
                    result = self.deal_file(sub_path)
                    # 将文件处理后的结果写入结果列表
                    data.append(result)

                else:  # 是文件夹, 就递归
                    self.search_folder(sub_path)

        else:
            return data

        return data

    def deal_file(self, sub_path):
        """自定义文件处理"""
        print(sub_path)
        data = " 1 {0}".format(sub_path)
        return data

    def write2txt(self, data, path=None, file_name='deal_result.txt'):
        """将数据写入txt文件"""
        if not path:
            path = self.desk_path
        root_path = path + "/WYH_FILES"
        # 如果文件夹存在不处理,否则新建一个文件夹
        if not os.path.exists(root_path):
            os.mkdir(root_path)

        # write data to file
        with open(root_path + '/' + file_name, mode='a+', encoding='utf-8') as f:
            f.write(data + '\n')

    def write2excel(self, data, path=None, file_name='deal_result.xls'):
        """将数据写入excel"""
        if not path:
            path = self.desk_path
        root_path = path + "/WYH_FILES"
        # 如果文件夹存在不处理,否则新建一个文件夹
        if not os.path.exists(root_path):
            os.mkdir(root_path)

        if not os.path.exists(root_path + '/' + file_name):
            work_book = xlwt.Workbook(encoding='utf-8')
            sheet = work_book.add_sheet('数据处理结果', cell_overwrite_ok=True)
            work_book.save(root_path + '/' + file_name)

        # 读取excel文件已写的行列
        work_book = xlrd.open_workbook(root_path + '/' + file_name, formatting_info=True)
        work_sheet = work_book.sheet_by_index(0)

        row_cnt = work_sheet.nrows
        print(row_cnt)
        col_cnt = work_sheet.ncols
        print(col_cnt)

        # 将数据写入excel
        wtbook = xlutils.copy.copy(work_book)
        wtsheet = wtbook.get_sheet(0)
        for col in range(len(data)):
            wtsheet.write(row_cnt, col, data[col])
        wtbook.save(root_path + '/' + file_name)


if __name__ == '__main__':
    worker = Worker()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值