目录
一.递归访问目录:目录中嵌套目录,有层次的列出所有的文件和文件夹
三.定义一个递归函数:打印菲波那契数列F(n)=F(n-1)+F(n-2)(n>=2,F(0)=0,F(1)=1)
一.递归访问目录:目录中嵌套目录,有层次的列出所有的文件和文件夹
先在D盘新建一个目录test,test目录中包含一个test1文件夹和test.txt文件,test1文件夹中包含test2和test.xsl,test2文件夹中包含test3和test.doc,test2文件夹中包含test3.txt
import os
def list_dir_content(dir_path, count=0):
for file_name in os.listdir(dir_path):
sub_path = os.path.join(dir_path, file_name)
if os.path.isdir(sub_path):
print(count * "\t" + file_name)
sub_count = count + 1
list_dir_content(sub_path, sub_count)
if os.path.isfile(sub_path):
print(count * "\t" + file_name)
list_dir_content("D:\\test")
print(os.getcwd())
#执行结果
test.txt.txt
test1
test.xls.xls
test2
test.doc.doc
test3
test3.txt.txt
D:\Python\python_code
二.定义一个嵌套函数
外层函数打印this is outing function
内层函数打印This is inner function
def outing():
print('this is outing fuction')
def inner():
print('this is inner fuction')
inner()
outing()
#执行结果
this is outing fuction
this is inner fuction