gpt-4-0314· openai
Suzhen/CodeChat
用Python递归的输出一个指定目录下除文件夹以外所有指定后缀文件的路径到一个记事本里
- User
用Python递归的输出一个指定目录下除文件夹以外所有指定后缀文件的路径到一个记事本里
- Assistant
首先,让我们编写一个递归地遍历指定目录下的所有文件的函数,叫做
find_files。import os def find_files(path, extension): files = [] for entry in os.scandir(path): if entry.is_file() and entry.name.endswith(extension): files.append(entry.path) elif entry.is_dir(): files.extend(find_files(entry.path, extension)) return files这个函数将会读取
path下的所有文件,如果找到一个有指定后缀的文件,就将它的路径添加到files列表中。当遇到一个文件夹时,我们就递归地对其调用find_files函数。现在我们可以通过调用这个函数来生成一个包含所有指定后缀文件路径的列表,然后将其保存到一个记事本文件中。
def save_to_file(file_paths, output_file): with open(output_file, 'w') as f: for path in file_paths: f.write('{}\n'.format(path)) def main(): path = input('Enter the path of the directory you want to search: ') extension = input('Enter the extension of the files you are looking for: ') output_file = input('Enter the name of the output file: ') file_paths = find_files(path, extension) save_to_file(file_paths, output_file) print(f'Paths of all {extension} files saved to {output_file}.') if __name__ == '__main__': main()
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.