面试题答案
一键面试import threading
def read_file(file_path, result_list):
with open(file_path, 'r', encoding='utf-8') as file:
content = file.read()
result_list.append(content)
def write_to_file(result_list, output_path):
with open(output_path, 'w', encoding='utf-8') as output_file:
for content in result_list:
output_file.write(content)
def main():
file_paths = ['file1.txt', 'file2.txt', 'file3.txt'] # 替换为实际文件路径
result_list = []
threads = []
for file_path in file_paths:
thread = threading.Thread(target=read_file, args=(file_path, result_list))
threads.append(thread)
thread.start()
for thread in threads:
thread.join()
output_path = 'output.txt' # 替换为实际输出文件路径
write_to_file(result_list, output_path)
if __name__ == "__main__":
main()
上述代码的主要步骤如下:
- 定义读取文件函数
read_file
:接收文件路径和结果列表作为参数,打开文件读取内容,并将内容添加到结果列表中。 - 定义写入文件函数
write_to_file
:接收结果列表和输出文件路径作为参数,打开输出文件,将结果列表中的内容依次写入文件。 - 定义主函数
main
:- 定义要读取的文件路径列表
file_paths
和用于存储文件内容的结果列表result_list
,以及线程列表threads
。 - 遍历文件路径列表,为每个文件创建一个线程来读取文件内容,将线程添加到线程列表并启动线程。
- 等待所有线程执行完毕(调用
join
方法)。 - 调用
write_to_file
函数将结果列表中的内容写入到输出文件。
- 定义要读取的文件路径列表
- 程序入口:通过
if __name__ == "__main__"
确保main
函数在直接运行脚本时执行。