1.递归访问目录: 且目录中嵌套目录,有层次的列出给定目录中所有的文件和文件夹
切换目录: os.chdir(path)
列出当前目录中所有的文件和文件夹 os.listdir(path), path: 绝对路径
判断是否是文件: os.path.isfile(path)
判断是否是目录: os.path.isdir(path)
拼接路径: os.path.join(path1, path2, path3…)
import os
os.chdir("E:\\test")
print(os.curdir)
print(os.path.abspath(os.curdir))
print(os.listdir(os.curdir))
def list_all_files(path, sep_count=1):
for sub_path in os.listdir(path):
if os.path.isfile(os.path.join(path, sub_path)):
print("--" * sep_count, sub_path, sep="")
if os.path.isdir(os.path.join(path, sub_path)):
print("--" * sep_count, sub_path, sep="")
list_all_files(os.path.join(path, sub_path), sep_count=sep_count + 1)
list_all_files("E:\\test")
2.定义一个嵌套函数,
外层函数打印this is outing function
内层函数功能:打印This is inner function
def outer():
def inner():
print("this is outing function")
print("This is inner function")
inner()
outer()
3.定义一个递归函数:打印斐波那契数列
F[n]=F[n-1]+Fn-2
def feibo_func(n):
if n == 1:
return 0
if n == 2:
return 1
if n > 2:
return feibo_func(n - 1) + feibo_func(n - 2)
list_data = []
for i in range(1, 20):
data = feibo_func(i)
list_data.append(data)
print(list_data)