1. Introduction
In the daily debugging process, it is often encountered that batches of source files are added. This article introduces a method of using python scripts to obtain all file directories and specified file names in a specified directory for reference.
Two, script introduction
import os
def get_dir_and_file(path, file_set, dir_set):
file_list = os.listdir(path)
for file in file_list:
#print(file)
cur_path = os.path.join(path, file)
if os.path.isdir(cur_path):
dir_set.add(cur_path)
get_dir_and_file(cur_path, file_set, dir_set)
else:
if file.endswith(".c"):
file_set.add(cur_path)
if file.endswith(".txt"):
file_set.add(cur_path)
if __name__ == "__main__":
file_set = set([])
dir_set = set([])
get_dir_and_file("./files", file_set, dir_set)
with open('./file_name.txt', 'w', encoding='utf-8') as f: # txtname 根据具体所需的命名即可
for val_name in file_set:
f.write(val_name + '\n')
with open('./dir_name.txt', 'w', encoding='utf-8') as f: # txtname 根据具体所需的命名即可
for val_name in dir_set:
f.write(val_name + '\n')
print('-----------------')
print(file_set)
print('-----------------')
print(dir_set)
print('finish!\r\n')
Three, summary
This article mainly introduces how to find the directory and file name under the specified path, and write it into the corresponding TXT file for reference. Welcome to discuss and exchange~