You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何利用多线程生成独立TXT文件?线程写入异常排查

问题分析与解决

你的代码出现文件写入混乱的核心原因是线程变量延迟绑定:
test函数中使用的i是主线程循环里的共享变量,线程执行到open(f'pri{i}.txt')时才会读取i的当前值。主线程启动第一个线程后,会继续执行循环将i更新为1,导致两个线程后续的写入操作都指向pri1.txt;只有第一个线程的第一次写入因为主线程还没完成i的更新,才写入了pri0.txt。

另外原代码还有一个小错误:循环中传递的args=[process[i]]里,process是已经关闭的文件对象,应该使用加载后的pro[i]。

修正后的代码

import time
import json
import threading
import itertools

limit = 10

# 将文件编号作为参数传入,让每个线程持有独立的编号
def test(process_data, file_idx):
    z = 0
    for _ in itertools.count(start=1):
        if z == limit:
            break
        z += 1
        time.sleep(1)
        # 使用线程专属的编号生成文件名
        with open(f'pri{file_idx}.txt', 'a') as file:
            file.write(process_data[f'user{z}'] + '\n')

# 加载JSON数据
with open('user.json') as f:
    pro = json.load(f)

process_count = 2
thread_list = []

for i in range(process_count):
    # 传入对应的数据块和文件编号
    t = threading.Thread(name=f'Account {i}', target=test, args=[pro[i], i])
    t.start()
    time.sleep(1)
    print(t.name + ' started')
    thread_list.append(t)

for thread in thread_list:
    thread.join()

修正后每个线程会使用自己的file_idx参数生成文件名,彻底避免变量共享导致的写入混乱,同时修复了文件对象调用的错误。

内容的提问来源于stack exchange,提问作者Don Eros

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 13:00:56