写在前面:最近在某视频网站学习java,视频中老师将所有知识点写在了当天代码文件夹下的txt文件中,我每天早晨复习的时候,要打开n多个目录才能找到要复习的全部内容,不胜其烦,因此写下此代码,将整个项目中所有的知识点txt文件内容统一写到一个新的txt文件中。
如图所示,只有以_teacher
为结尾的文件夹下的txt文件记录有内容。
|–JavaCode
|-----Chaper01
|--------src
|--------------one
|-----------------01-数组概述.txt
|--------------two
|-----------------02-数组的基本使用.txt
|-----Chaper01_teacher
|--------src
|-----------package01
|--------------one
|-----------------01-数组概述.txt
|--------------two
|-----------------02-数组的基本使用.txt
import os
# teacher文件夹递归
def search_teacher_dir(dir_path):
result = []
file_list = os.listdir(dir_path)
for file_name in file_list:
file_name = os.path.join(dir_path,file_name)
if os.path.isdir(file_name):
result.extend(search_teacher_dir(file_name))
if os.path.isfile(file_name):
result.append(file_name)
return result
#获取当前目录下所有文件和文件夹
def search_files(dir_path):
result = []
file_list = os.listdir(dir_path)
for file_name in file_list:
file_name = os.path.join(dir_path,file_name)
if os.path.isdir(file_name): # 判断是否是文件夹
if(file_name.endswith("_teacher")): # 记录以‘_teacher’结尾的文件夹
result.extend(search_teacher_dir(file_name))
if os.path.isfile(file_name):
result.append(file_name)
return result
#记录所有知识点txt文件
def search_txts(dir_path):
txt_list = []
file_list = search_files(dir_path)
for file_name in file_list:
file_path = file_name.split('\\')
#知识点记录在以‘0’开头的txt文件中
if file_path[-1].startswith('0') and file_name.endswith(".txt"):
txt_list.append(file_name)
return txt_list
#读取所有知识点txt文件,并将内容写到一个新的txt文件中
def write_txt(dir_path,new_file):
txt_list = search_txts(dir_path)
for txt_file in txt_list:
print(txt_file)
content = ''
with open(txt_file,'r',encoding="utf-8") as f:
content = f.read()
with open(new_file,'a',encoding="utf-8") as f:
f.write(content)
if __name__ == "__main__":
dir_path = "D:\\notes\\javacode\\JavaCode" #指定遍历目录
new_file = "D:\\notes\\javacode\\JavaCode\\all_notes.txt" #记录所有知识点的新txt文件
write_txt(dir_path,new_file)