지정된 디렉토리에서 파일 디렉토리와 파일 이름을 가져오는 Python 스크립트

1. 소개

일상적인 디버깅 과정에서 소스 파일의 배치가 추가되는 경우가 종종 있는데, 이 기사에서는 Python 스크립트를 사용하여 모든 파일 디렉토리와 지정된 디렉토리의 지정된 파일 이름을 참조용으로 가져오는 방법을 소개합니다.

둘, 대본 소개

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')

셋, 요약

이 문서는 주로 지정된 경로 아래의 디렉토리 및 파일 이름을 찾는 방법과 참조를 위해 해당 TXT 파일에 쓰는 방법을 소개합니다. 토론 및 교환을 환영합니다 ~

추천

출처blog.csdn.net/xuxu_123_/article/details/131067105