博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
python实例31[列出目录下所有的文件到txt]
阅读量:4599 次
发布时间:2019-06-09

本文共 1197 字,大约阅读时间需要 3 分钟。

代码: (使用os.listdir) 

import os
def ListFilesToTxt(dir,file,wildcard,recursion):
    exts = wildcard.split(" ")
    files = os.listdir(dir)
    for name in files:
        fullname=os.path.join(dir,name)
        if(os.path.isdir(fullname) & recursion):
            ListFilesToTxt(fullname,file,wildcard,recursion)
        else:
            for ext in exts:
                if(name.endswith(ext)):
                    file.write(name + "\n")
                    break
def Test():
  dir="J:\\1"
  outfile="binaries.txt"
  wildcard = ".txt .exe .dll .lib"
  
  file = open(outfile,"w")
  if not file:
    print ("cannot open the file %s for writing" % outfile)
  ListFilesToTxt(dir,file,wildcard, 1)
  
  file.close()
Test()

 

 

代码:(使用os.walk) walk递归地对目录及子目录处理,每次返回的三项分别为:当前递归的目录,当前递归的目录下的所有子目录,当前递归的目录下的所有文件

import os
def ListFilesToTxt(dir,file,wildcard,recursion):
    exts = wildcard.split(" ")
    for root, subdirs, files in os.walk(dir):
        for name in files:
            for ext in exts:
                if(name.endswith(ext)):
                    file.write(name + "\n")
                    break
        if(not recursion):
            break
def Test():
  dir="J:\\1"
  outfile="binaries.txt"
  wildcard = ".txt .exe .dll .lib"
  
  file = open(outfile,"w")
  if not file:
    print ("cannot open the file %s for writing" % outfile)
  ListFilesToTxt(dir,file,wildcard, 0)
  
  file.close()
Test()

 

 

 

欢迎大家改进共享!

 

转载于:https://www.cnblogs.com/L-H-R-X-hehe/p/3815362.html

你可能感兴趣的文章
vue-v-for
查看>>
易游数据劫持获取和易游取数据工具
查看>>
剑指offer——最小的K个数
查看>>
python将PNG格式的图片转化成为jpg
查看>>
C++学习笔记-const
查看>>
C学习笔记-小程序(长期更新)
查看>>
关于listView 中的聚焦问题
查看>>
Shiro学习(总结)
查看>>
C指针解析 ------ 指针的算术运算
查看>>
rabbitmq安装与高可用集群配置
查看>>
英语-托福英语学习(单词一)
查看>>
QCC3003x BLE 设置私有地址
查看>>
Oracle SQL
查看>>
Webkit内核自定义滚动条样式
查看>>
JSP转发和重定向的区别
查看>>
简单使用JSON,通过JSON 字符串来创建对象(二)
查看>>
Codeforces Round #178 (Div. 2) C. Shaass and Lights
查看>>
windows蓝屏代码
查看>>
Chapter 3 Phenomenon——16
查看>>
15款免费艺术院校学生求职简历word模板,四页求职简历模板,含自荐信
查看>>