python如何读取多层嵌套文件夹中的文件

  介绍

这篇文章给大家分享的是有关python如何读取多层嵌套文件夹中的文件的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。

python是什么意思

python是一种跨平台的,具有解释性,编译性,互动性和面向对象的脚本语言,其最初的设计是用于编写自动化脚本,随着版本的不断更新和新功能的添加,常用于用于开发独立的项目和大型项目。

由于工作安排,需要读取多层文件夹下嵌套的文件,文件夹的结构如下图所示:

 python如何读取多层嵌套文件夹中的文件

想到了递归函数,使用python的os.path.isfile方法判断当前是不是可执行文件,如果不是再用操作系统。listdir方法将子目录循环判断。

<强>代码如下

import 操作系统   时间=path  & # 39; abc # 39;   时间=path_read  [],, # path_read  saves  all  executable 文件      def  check_if_dir (file_path):   temp_list 才能=,os.listdir (file_path),, # put  file  name 得到file_path  temp_list拷贝   for 才能;temp_list_each  temp_list:拷贝   ,,,if  os.path.isfile(时间+ file_path  & # 39;/& # 39;, +, temp_list_each):   ,,,,,temp_path =, file_path  +, & # 39;/& # 39;, + temp_list_each   ,,,,,if  os.path.splitext (temp_path) [1],==, & # 39; . log # 39;:,, #自己需要处理的是. log文件所以在此加一个判断   ,,,,,,,path_read.append (temp_path)   ,,,,,其他的:   ,,,,,,,继续   ,,,:   ,,,,,check_if_dir(时间+ file_path  & # 39;/& # 39;, +, temp_list_each), # loop 遍历      check_if_dir(路径)   #打印(path_read)

实现思想就是把所有可执行文件的路径,通过字符串的拼,接完整的放进一个列表中,在后面的执行步骤中依次提取进行访问和操作。

由于自己拿到的数据集中,一个文件夹下要么全是文件夹,要么全是文件,所以在第一次写这个函数时,通过temp_list[0]直接判断列表中第一个文件是不是文件。

所以自己第一次写的代码有一个很大的错误,就是当一个文件夹下既有文件夹又有文件的情况下,会尝试将一个文件夹按照文件读取,报错。

第一次代码如下:

import 操作系统   时间=path  & # 39; abc # 39;   时间=path_read  [],, # path_read  saves  all  executable 文件      def  check_if_dir (file_path):   temp_list 才能=,os.listdir (file_path),, # put  file  name 得到file_path  temp_list拷贝      if 才能;os.path.isfile(时间+ file_path  & # 39;/& # 39;, +, temp_list[0]):,, #此处直接判断列表中第一项是不是文件   ,,,for  temp_list_each 拷贝temp_list:   ,,,,,temp_path =, file_path  +, & # 39;/& # 39;, + temp_list_each   ,,,,,if  os.path.splitext (temp_path) [1],==, & # 39; . log # 39;:   ,,,,,,,path_read.append (temp_path)   ,,,,,其他的:   ,,,,,,,继续   其他的才能:   ,,,for  temp_list_each 拷贝temp_list:   ,,,,,check_if_dir(时间+ file_path  & # 39;/& # 39;, +, temp_list_each), # loop 遍历      check_if_dir(路径),,# put  all  path  path_read拷贝   #打印(path_read)

感谢各位的阅读!关于“python如何读取多层嵌套文件夹中的文件”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,让大家可以学到更多知识,如果觉得文章不错,可以把它分享出去让更多的人看到吧!

python如何读取多层嵌套文件夹中的文件