pthon- recursive real - manipulate files

Recursive function, depth access to all the subdirectories and files in a sub-path

Recursive loop VSwhile

Points while loop

  1. Outside the loop to the initial conditions
  2. Reasonable cycling conditions (when the conditions are not met, will quit, that a clear exit cycle time)
  3. There must be changes to the internal circulation conditions

Points recursive function

Internal function calls itself

There must be an exit opportunity to return

It can be compared to an infinite loop

Infinite loop format

while True:
	要做的事件
	if 条件:
		break

Recursive format

def func(arg):
	要做的事件
	if 条件:
		return
	func(arg2)

func(实参)

Recursive function chart

Here Insert Picture Description

Case, a recursive process each file

Examples of the present example applies only to the classroom, understanding

import os

from bin  import file

total_list = []

# 把一个文件转为列表包字典
def trans_txt_2_list(file_path):
    data_list = file.File().format_txt2data(file_path)
    return data_list


def get_deep_list(path):
    list_dir = os.listdir(path)
    for member in list_dir:
        new_path = os.path.join(path, member)
        if os.path.isdir(new_path):
            get_deep_list(new_path)
        else:
            data_list = trans_txt_2_list(new_path)
            total_list.extend(data_list)
            print("当前总题数%d" %len(total_list))


get_deep_list(os.getcwd())

for i in total_list:
    print(i)

Guess you like

Origin blog.csdn.net/ifubing/article/details/94380805