递归理解和demo
递归即程序调用自身,注意一定有一种可以退出程序的情况;
例子:遍历获取目录下的所有子目录和文件
1)使用python实现
"""
@author :Eric-chen
@contact :sygcrjgx@163.com
@time :2017/5/07 11:08
@desc :递归小例子,查看当前目录下所有的子目录和文件
"""
import os
from time import time
dir_count = 0
file_count = 0
def get_all_dir(path):
# 得到当前目录下所有的文件
fills_list = os.listdir(path)
# 处理每一个文件
for file_name in fills_list:
# 判断是否是路径(用绝对路径)
file_abs_path = os.path.join(path, file_name)
if os.path.isdir(file_abs_path):
global dir_count # 写了这个global,不知道会不会被开除
dir_count += 1
print(path + '\\' + file_name)
get_all_dir(file_abs_path)
else:
global file_count
file_count += 1
print(path + '\\' + file_name)
def main():
user_dir = r"D:\桌面"
t1 = time()
get_all_dir(user_dir)
t2 = time()
print("一共有%d个目录,%d个文件,耗时%.3f秒" % (dir_count, file_count, t2 - t1))
if __name__ == "__main__":
main()
2)使用java实现
package method;
import java.io.File;
public class test {
public static void main(String[] args) {
String path = "D:\\桌面";
File file = new File(path);
listAllFiles(file);
}
private static void listAllFiles(File file) {
if (file.isDirectory()) {
File[] files = file.listFiles();
for (int i = 0; i < files.length; i++) {
if (files[i].isDirectory()) {
listAllFiles(files[i]);
System.out.println(files[i].getAbsoluteFile());
} else {
System.out.println(files[i].getAbsolutePath());
}
}
}else {
System.out.println(file.getAbsolutePath());
}
}
}
We only live once, and time just goes by.

浙公网安备 33010602011771号