当前位置:首页 » python教程 » 正文

python读取多层嵌套文件夹中的文件实例

看: 954次  时间:2020-08-11  分类 : python教程

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

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

代码如下

import os
path = 'abc'
path_read = []  #path_read saves all executable files

def check_if_dir(file_path):
  temp_list = os.listdir(file_path)  #put file name from file_path in temp_list
  for temp_list_each in temp_list:
    if os.path.isfile(file_path + '/' + temp_list_each):
      temp_path = file_path + '/' + temp_list_each
      if os.path.splitext(temp_path)[-1] == '.log':  #自己需要处理的是.log文件所以在此加一个判断
        path_read.append(temp_path)
      else:
        continue
    else:
      check_if_dir(file_path + '/' + temp_list_each)  #loop traversal

check_if_dir(path)
#print(path_read)

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

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

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

第一次代码如下:

import os
path = 'abc'
path_read = []  #path_read saves all executable files

def check_if_dir(file_path):
  temp_list = os.listdir(file_path)  #put file name from file_path in temp_list

  if os.path.isfile(file_path + '/' + temp_list[0]):  #此处直接判断list中第一项是不是文件
    for temp_list_each in temp_list:
      temp_path = file_path + '/' + temp_list_each
      if os.path.splitext(temp_path)[-1] == '.log':
        path_read.append(temp_path)
      else:
        continue
  else:
    for temp_list_each in temp_list:
      check_if_dir(file_path + '/' + temp_list_each)  #loop traversal

check_if_dir(path)  #put all path in path_read
#print(path_read)

以上这篇python读取多层嵌套文件夹中的文件实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持python博客。

<< 上一篇 下一篇 >>

搜索

推荐资源

  Powered By python教程网   鲁ICP备18013710号
python博客 - 小白学python最友好的网站!