首页 > 编程语言 >python: FileHelper

python: FileHelper

时间:2023-07-09 20:56:15浏览次数:39  
标签:return python os self print path FileHelper def

 

# encoding: utf-8
# 版权所有 2023 涂聚文有限公司
# 许可信息查看:
# 描述:
# Author    : geovindu,Geovin Du 涂聚文.
# IDE       : PyCharm 2023.1 python 311
# Datetime  : 2023/7/9 19:12
# User      : geovindu
# Product   : PyCharm
# Project   : pythonTkinterDemo
# File      : FileLib.py
# explain   : 学习


import os
import sys
import shutil
from PIL import Image,ImageSequence
import glob
import pyzbar.pyzbar as p
import pyqrcode
import qrcode




class FileHelper(object):
    """
    简单的文件帮助
    """
    global cdir
    global cfile
    global allfiles
    def __init__(self):
        self.__path=""
        self.cdir=1
        self.cfile=1
        self.allfiles=list()
    @property
    def Path(self):
        return self.__path

    @Path.setter
    def Path(self,path):
        self.__path=path

    def dirAllFile(self,pathname):
        """
        迭代遍历文件夹下的子文件夹和文件  iterate 
        :param pathname: 文件夹的地址
        :return:返回最后一次文件夹的文件
        """
        files = list()
        if os.path.exists(pathname):
            filelist = os.listdir(pathname)
            for f in filelist:
                f = os.path.join(pathname, f)
                if os.path.isdir(f):
                    self.cdir+=1
                    self.dirAllFile(f)
                else:
                    dirname = os.path.dirname(f)
                    baseName = os.path.basename(f)
                    if os.path.isfile(f):
                        files.append(f)
                        self.cfile+=1

        self.allfiles.append(files)
        return files #最后一次遍历的


    def traversalFiles(self):
        """
        只是当前文件夹下的,子文件夹的没有列出
        :return:
        """
        dirs=[]
        files=[]
        #global cdir=1
        #global cfile=1
        for item in os.scandir(self.__path):
            if item.is_dir():
                dirs.append(item.path)
                cdir+=1

            elif item.is_file():
                files.append(item.path)
                cfile+=1

        #traversalFiles(self)
        print('dirs:')
        print('\n'.join(dirs))

        print()

        print('files:')
        print('\n'.join(files))
        print(f"文件夹个数:{cdir},文件个数:{cfile}:")

    def displayFileLsit(self):
        """

        :return:
        """
        paths = os.walk(f'{self.__path}')
        cou = 0
        for path, dir_lst, file_lst in paths:
            for file_name in file_lst:
                print(os.path.join(path, file_name))
                cou += 1
        print("共有文件:", cou)



    # 创建文件方法
    def mkdirFile(self, writestring:str):
        """
        没有文件夹创建,把内容写入TEXT文本文件中
        :param folder: 文件夹名称
        :param writestring: 要写的内容
        :return: None
        """
        i = 1
        while True:
            # 判断是否文件存在,如果不存在则创建,存在则改名
            f_p_intact = self.__path + "\\geovindu" + str(i) + ".txt"
            # 打印完整文件名称
            print("已创建的文件是:",f_p_intact)
            if not os.path.exists(f_p_intact):
                # 文件的写操作
                f = open(f_p_intact, "w+",encoding='utf8')
                f.write(writestring)
                # 关闭文件流
                f.close()
                break
            else:
                i += 1

    def makeGif(self):
        """
        生成GIF动画图片
        :param framefolder: 文件夹
        :return:
        """
        images = glob.glob(f"{self.__path}/*.png")
        images.sort()
        frames = [Image.open(image) for image in images]
        frame_one = frames[0]
        print(frame_one)
        frame_one.save(framefolder+"/geovindu.gif", format="gif", append_images=frames,
                       save_all=True, duration=50, loop=0)

    def generateQrCode(self,qrcodestr:str,qrcodefile:str):
        """
        生成二维码
        :param qrcodestr:  二要生成的二给码字符
        :param qrcodefile: 生成的文件名
        :return:
        """
        img = qrcode.make(qrcodestr)
        type(img)
        img.save(f'{qrcodefile}.png')

    def readQrCode(self,qrcodefile:str):
        """
        读二维码
        :param qrcodefile: 二维码文件名
        :return: 返回二维码内容
        """
        nowpath = os.getcwd()
        scrimg=Image.open(f"{nowpath}\{qrcodefile}.png")
        m=p.decode(scrimg)
        codedata=m[0].data.decode("utf-8")
        return codedata

  

调用:

    nowpath = os.getcwd()
    f=Common.FileLib.FileHelper()
    f.Path=nowpath
    #f.displayFileLsit()
    #f.traversalFiles()
    files=f.dirAllFile(nowpath)
    allf=f.allfiles
    print(len(allf))
    for ff in allf:
        for df in ff:
            if not df==[]:
                print(df)
    print(f"文件夹数量:{f.cdir}  文件数量:{f.cfile}")

  

 

标签:return,python,os,self,print,path,FileHelper,def
From: https://www.cnblogs.com/geovindu/p/17539349.html

相关文章

  • Windows上部署Python flask项目
    最近使用Pythonflask做了一个项目要部署,网上一大堆教程没有一个完整,最后看了多个教程才配置完成,下面根据自己的环境整理一下做个备忘录环境:Windows10apachehttpd-2.4.54(vc++我从2008-2022全装了)Python3.11(环境变量别忘了配)MySQL8.0.31(项目中用到了数据库)上面的环境需要......
  • python实现字符输入实时读取
    原理:通过opencv中的waitKey来实现示例代码:defkey_control():while1:cv2.imshow('tmp',np.zeros(shape=(100,100,3),dtype=np.uint8))key=cv2.waitKey(1)ifkey==ord('w'): print("w")elif......
  • Python调用 JS -PyExecJS, Python 调用 JS -js2py
    Python调用JS-PyExecJS日常Web端爬虫过程中,经常会遇到参数被加密的场景,因此,我们需要分析网页源代码通过调式,一层层剥离出关键的JS代码,使用Python去执行这段代码,得出参数加密前后的Python实现//计算两个数的和functionadd(num1,num2){returnnum1+num2;}......
  • Python | 认识编码
    编码(Encoding)是将字符转换为计算机可以处理的二进制数据的过程。在计算机中,所有的文本都是以二进制形式存储的,因此需要使用编码将文本转换为二进制数据。Python中的编码指的是将字符串转换为字节串(bytes)的过程,或将字节串转换为字符串的过程。编码与解码在Python中,字符串是以......
  • python打包Windows.exe程序(pyinstaller)
    python打包Windows.exe程序(pyinstaller)基础命令pipinstallpyinstaller使用pip命令来安装pyinstaller模块。-F:pyinstaller-Fhello.py-phello2.py-D:pyinstaller-Dhello.py-phello2.py-i:pyinstaller-itb.ico-Fhello.py-phello2.py其中前一个文件hel......
  • python获取小红书web_session,以及解决x-s签名验证(2023-07-09)
    一、web_session请求接口:https://edith.xiaohongshu.com/api/sns/web/v1/login/activate请求类型:post提交数据:{}这儿是两个字符{},笔者最初提交None,总得不到结果,chromeF12才发现需要这两个字符。二、签名验证x-s 该请求需要x-s签名验证,签名代码如下:a1="186d30820a4......
  • python:File
     defgetFile(prefixletter:str,ok:bool):"""文件名添加后缀:paramprefixletter::paramok:True增加后缀,否则为删除:return:"""try:nowfoloder=os.getcwd()curpath=os.path.join(nowfoloder,r&q......
  • python - 函数(二)
    4.传递列表defgreet_users(names):"""向列表中的每位用户发出问候。"""fornameinnames:msg=f"Hello,{name.title()}"print(msg)usernames=['hanks','jackson','jimmy']......
  • 中转转运运输问题——Python实现
    在供应链中,中转运输是一项关键活动,用于解决商品在运输过程中的各种限制和需求。商业部门承担中转运输的责任,组织商品的再次发运,以确保顺利的货物流动。中转运输在供应链中具有重要作用,主要原因如下:物流条件限制:由于运输条件的限制,商品可能无法直接一次性运送到目的地。这可能涉......
  • python - 函数(一)
    1.示例defgreet_user():#函数定义"""显示简单的问候语"""#文档字符串,描述了函数的功能。Python基于此生成有关函数的文档print("Hello!")greet_user()1.1参数defgreet_user(username):"""显示简单的问候语"&......