MST

星途 面试题库

面试题:Python文件处理与多线程之基础运用

请编写一个Python程序,使用多线程读取多个文本文件的内容,并将这些内容合并写入到一个新的文件中。要求展示如何创建线程、管理线程执行以及处理文件I/O操作。
28.8万 热度难度
编程语言Python

知识考点

AI 面试

面试题答案

一键面试
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()

上述代码的主要步骤如下:

  1. 定义读取文件函数read_file:接收文件路径和结果列表作为参数,打开文件读取内容,并将内容添加到结果列表中。
  2. 定义写入文件函数write_to_file:接收结果列表和输出文件路径作为参数,打开输出文件,将结果列表中的内容依次写入文件。
  3. 定义主函数main
    • 定义要读取的文件路径列表file_paths和用于存储文件内容的结果列表result_list,以及线程列表threads
    • 遍历文件路径列表,为每个文件创建一个线程来读取文件内容,将线程添加到线程列表并启动线程。
    • 等待所有线程执行完毕(调用join方法)。
    • 调用write_to_file函数将结果列表中的内容写入到输出文件。
  4. 程序入口:通过if __name__ == "__main__"确保main函数在直接运行脚本时执行。