zoukankan      html  css  js  c++  java
  • python统计目录和目录下的文件,并写入excel表

    运营那边提出需求,有些媒体文件需要统计下

    目录结构大概是这样的

    每个目录下面都有很多文件,目录下面没子目录

     我这里是模拟下创建的目录和文件,和运营那边说的目录结构都是一致的

    想最终统计结果如下格式

    我的思路如下。

    这里肯定用到了操作excel的模块以及遍历目录的模块

    搜索相关遍历目录的有os.walk不错

    先练习下它

    从结构上来看,for root, dirs, files in os.walk(...),很容易让人认为os.walk(...)生成了一个迭代器。迭代器的next方法可能会返回下一层次的文件夹内容。事实上,os.walk()是一个生成器函数。

    关于生成器转自下面

    https://www.zhihu.com/question/20829330

    从结构上来看,for root, dirs, files in os.walk(...),很容易让人认为os.walk(...)生成了一个迭代器。迭代器的next方法可能会返回下一层次的文件夹内容。

    事实上,os.walk()是一个生成器函数。生成器与迭代器,是Python引入的几大特性之一,而生成器要比迭代器高级一些。至于生成器的工作原理和适用场合,可以先从os.walk()的源码说起。

    >>> def func(n):
    ...     yield n*2
    ...
    >>> func
    <function func at 0x00000000029F6EB8>
    >>> g = func(5)
    >>> g
    <generator object func at 0x0000000002908630>
    >>>
    

      

     func 就是一个生成器函数,调用该函数时返回对象就是生成器 g ,这个生成器对象的行为和迭代器是非常相似的,可以用在 for 循环等场景中。注意 yield 对应的值在函数被调用时不会立刻返回,而是调用next方法时(本质上 for 循环也是调用 next 方法)才返回

    >>> g = func(5)
    >>> next(g)
    10
    
    >>> g = func(5)
    >>> for i in g:
    ...     print(i)
    ...
    10
    

      

     那为什么要用生成器呢?显然,用生成器在逼格上要比迭代器高几个等级,它没有那么多冗长代码了,而且性能上一样的高效,为什么不用呢?来看看用生成器实现斐波那契数列有多简单。

    def fib(n):
        prev, curr = 0, 1
        while n > 0:
            n -= 1
            yield curr
            prev, curr = curr, curr + prev
    
    print([i for i in fib(10)])
    #[1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
    

       

    生成器表达式

    器表达式与列表推导式长的非常像,但是它俩返回的对象不一样,前者返回生成器对象,后者返回列表对象。

    >>> g = (x*2 for x in range(10))
    >>> type(g)
    <type 'generator'>
    >>> l = [x*2 for x in range(10)]
    >>> type(l)
    <type 'list'>
    

      

     所以os.walk是生成器函数,可以使用for迭代它

    也可以使用next单次获取结果

    # -*- coding:utf-8 -*-
    import os
    
    dir1='D:Pywork总目录'
    list1=[]
    inter=os.walk(dir1,topdown=True)
    print(inter)
    print(next((inter)))
    print(next((inter)))
    print(next((inter)))
    

      

    结果如下

    每次执行结果都是一个三元组,第一个是被遍历的目录,第二个是此目录下的子目录列表,第三个此目录下的子文件列表

    excel表里,我需要的就是这个列表里的子目录名,以及子目录的文件名

    # -*- coding:utf-8 -*-
    import os
    
    dir1='D:Pywork总目录'
    list1=[]
    for par,dirs1,files1 in os.walk(dir1,topdown=True):
        print(par,'---------',dirs1,'++++++++',files1)
        list1.append(dirs1)
    print('list1---------------------------')
    print(list1[0])
    for zi in  list1[0]:
        print(dir1+'\'+zi)
    

      

    运行结果如下

     获取子目录以及子目录的文件,打印下

    这里先把excel的注释了

    # -*- coding:utf-8 -*-
    
    import os
    import xlwt
    #写个配置文件,通过它获取目录
    def get_dir():
        try:
            with open(r'D:Pyworkmulu.txt', 'r') as f :
                print(f.readline())
                return f.readline()
        except Exception as e:
            print("文件格式有误,或者文件名不对----"+e)
    # 创建 xls 文件对象
    wb = xlwt.Workbook()
    # 新增一个表单
    sh = wb.add_sheet('文件信息')
    # 按位置添加数据
    dir_col=0
    file_col=1
    row_init=0
    #从配置获取目录名
    dir=get_dir()
    for parent1, dir_names1, file_names1 in os.walk(dir):
        for dir_name1 in dir_names1:
            for parent2,dir_names2,file_names2 in os.walk(dir+dir_name1):
                for file_name2 in file_names2:
                    # sh.write(row_init,dir_col,dir_name1)
                    # sh.write(row_init,file_col,file_name2)
                    # row_init=row_init+1
                    print(dir_name1,file_name2)
    # wb.save("文件信息结果.xls")
                    # print(dir_name1,file_name2)
    

      

     上面是通过配置文件方式获取要被操作的目标目录

     写入excel运行测试成功

    # -*- coding:utf-8 -*-
    import os
    import xlwt
    #写个配置文件,通过它获取目录
    def get_dir():
        try:
            with open(r'D:Pyworkmulu.txt', 'r') as f :
                print(f.readline())
                return f.readline()
        except Exception as e:
            print("文件格式有误,或者文件名不对----"+e)
    # 创建 xls 文件对象
    wb = xlwt.Workbook()
    # 新增一个表单
    sh = wb.add_sheet('文件信息')
    # 按位置添加数据
    dir_col=0
    file_col=1
    row_init=0
    #从配置获取目录名
    dir=get_dir()
    for parent1, dir_names1, file_names1 in os.walk(dir):
        for dir_name1 in dir_names1:
            for parent2,dir_names2,file_names2 in os.walk(dir+dir_name1):
                for file_name2 in file_names2:
                    sh.write(row_init,dir_col,dir_name1)
                    sh.write(row_init,file_col,file_name2)
                    row_init=row_init+1
                    # print(dir_name1,file_name2)
    wb.save("文件信息结果.xls")
    

      

     

    改良下代码,因为我想把这个py脚本打成exe程序,交给运营。不然每次需要我帮他们弄,太麻烦我了

    # -*- coding:utf-8 -*-
    
    #exe直接丢入父级目录下
    import os
    import xlwt
    
    #定义个获取目录的函数。没用到
    def get_dir():
        return os.getcwd()
    # 创建 xls 文件对象
    wb = xlwt.Workbook()
    # 新增一个表单
    sh = wb.add_sheet('子目录文件信息')
    # 按位置添加数据,col表示列的意思
    dir_col=0
    file_col=1
    row_init=0
    #从配置获取目录名,这里并没用到。因为程序就在目标目录下。可以重新赋值为.
    dir=get_dir()
    dir="."
    for parent1, dir_names1, file_names1 in os.walk(dir):
        for dir_name1 in dir_names1:
            for parent2,dir_names2,file_names2 in os.walk(dir+'\'+dir_name1):
                for file_name2 in file_names2:
                    sh.write(row_init,dir_col,dir_name1)
                    sh.write(row_init,file_col,file_name2)
                    row_init=row_init+1
    wb.save("子目录文件统计.xls")
    

      

     把此py脚本打成exe文件


    需要用到PyInstaller以及pywin32

     下载的pywin32和PyInstaller为

    pywin32-221.win32-py3.5.exe

    PyInstaller-3.1.1.tar.gz

    Python是没有自带访问windows系统API的库的,需要下载。库的名称叫pywin32,可以从网上直接下载。
    以下链接地址可以下载:http://sourceforge.net/projects/pywin32/files%2Fpywin32/ (下载适合你的Python版本)

    它会自动检测你的python解释器路径并进行安装(前提是环境变量配置好了)

    以下是安装过程,不用设置环境变量,它会自动检测你python的环境变量
    然后自动安装到第三方插件里

     

    关于PyInstaller-3.1.1.tar.gz的安装

    我放在下面路径下了。没特殊要求

     解压并安装

    我的win10安装如下
    D:ProgramsPythonPyInstaller-3.1.1>python setup.py install
    

      

     

    执行   

    PyInstaller -F 子目录文件统计.py

    -F执行py文件路径

    最好exe程序在下面路径

    注意下面的执行路径

    D:ProgramsPythonPyInstaller-3.1.1dist子目录文件统计.exe

    D:ProgramsPythonPyInstaller-3.1.1>PyInstaller -F 子目录文件统计.py
    77 INFO: PyInstaller: 3.1.1
    123 INFO: Python: 3.5.2
    125 INFO: Platform: Windows-10-10.0.16299-SP0
    128 INFO: wrote D:ProgramsPythonPyInstaller-3.1.1子目录文件统计.spec
    135 INFO: UPX is not available.
    137 INFO: Extending PYTHONPATH with paths
    ['D:\Programs\Python\PyInstaller-3.1.1',
     'D:\Programs\Python\PyInstaller-3.1.1']
    144 INFO: checking Analysis
    156 INFO: Building because D:ProgramsPythonPyInstaller-3.1.1子目录文件统计.py changed
    158 INFO: Initializing module dependency graph...
    161 INFO: Initializing module graph hooks...
    172 INFO: Analyzing base_library.zip ...
    2429 INFO: running Analysis out00-Analysis.toc
    2596 WARNING: lib not found: api-ms-win-crt-process-l1-1-0.dll dependency of D:ProgramsPythonPython35-32python35.dll
    
    2692 WARNING: lib not found: api-ms-win-crt-conio-l1-1-0.dll dependency of D:ProgramsPythonPython35-32python35.dll
    3031 INFO: Analyzing D:ProgramsPythonPyInstaller-3.1.1子目录文件统计.py
    3380 INFO: Looking for import hooks ...
    3384 INFO: Processing hook   hook-encodings.py
    3394 INFO: Processing hook   hook-pydoc.py
    3395 INFO: Processing hook   hook-xml.py
    3581 INFO: Looking for ctypes DLLs
    3587 INFO: Analyzing run-time hooks ...
    3599 INFO: Looking for dynamic libraries
    3687 WARNING: lib not found: api-ms-win-crt-conio-l1-1-0.dll dependency of D:ProgramsPythonPython35-32DLLs\_ssl.pyd
    3827 WARNING: lib not found: api-ms-win-crt-conio-l1-1-0.dll dependency of D:ProgramsPythonPython35-32DLLs\_hashlib.
    pyd
    3863 INFO: Looking for eggs
    3863 INFO: Using Python library D:ProgramsPythonPython35-32python35.dll
    3863 INFO: Found binding redirects:
    []
    3881 INFO: Warnings written to D:ProgramsPythonPyInstaller-3.1.1uild子目录文件统计warn子目录文件统计.txt
    3892 INFO: checking PYZ
    3894 INFO: Building because toc changed
    3895 INFO: Building PYZ (ZlibArchive) D:ProgramsPythonPyInstaller-3.1.1uild子目录文件统计out00-PYZ.pyz
    4178 INFO: checking PKG
    4180 INFO: Building because toc changed
    4180 INFO: Building PKG (CArchive) out00-PKG.pkg
    5477 INFO: Bootloader D:ProgramsPythonPython35-32libsite-packagespyinstaller-3.1.1-py3.5.eggPyInstallerootloade
    rWindows-32bit
    un.exe
    5478 INFO: checking EXE
    5479 INFO: Building because out00-EXE.toc is bad
    5490 INFO: Building EXE from out00-EXE.toc
    5495 INFO: Appending archive to EXE D:ProgramsPythonPyInstaller-3.1.1dist子目录文件统计.exe
    
    D:ProgramsPythonPyInstaller-3.1.1>
    

      

     注意!!!存储py文件的时候必须是如下格式

    否则打包成exe的时候,会无法成功

    把exe程序拿出来

     复制放到这里

     退出杀毒软件,双击运行

    生成xls文件

    双击打开

  • 相关阅读:
    CodeForces Gym 100500A A. Poetry Challenge DFS
    CDOJ 486 Good Morning 傻逼题
    CDOJ 483 Data Structure Problem DFS
    CDOJ 482 Charitable Exchange bfs
    CDOJ 481 Apparent Magnitude 水题
    Codeforces Gym 100637G G. #TheDress 暴力
    Gym 100637F F. The Pool for Lucky Ones 暴力
    Codeforces Gym 100637B B. Lunch 找规律
    Codeforces Gym 100637A A. Nano alarm-clocks 前缀和
    TC SRM 663 div2 B AABB 逆推
  • 原文地址:https://www.cnblogs.com/nmap/p/8962021.html
Copyright © 2011-2022 走看看