python - 如何使用线程同时读取文件
问题描述
我有两个文件employeename 和employee address 读取这两个文件并想要预期的输出:
Jhon Pitroda
Mumbai
Rinkal
Hubali
我编写代码但输出不是实际的,因为我想要使用线程如何实现,我是编程新手。
任何人都可以帮助我,提前谢谢你。
from time import sleep
from threading import *
class EmpInfoMerger(Thread):
# write data from text file to temp file
def write_to_temp_file(self,file_path,mode):
with open(file_path,mode) as filein:
with open('temp_file.txt', 'a+') as fileout:
for line in filein:
fileout.write(line)
print(line)
sleep(1)
filein.close()
fileout.close()
def write_to_file(self,file_path,mode):
read_file = open("temp_file.txt", "r+")
data_input = read_file.read()
# A output file to print temp data to file
write_file = open(file_path, mode)
write_file.write(data_input)
print("file contents are written from temp_file to output_file and temp_file contents are deleted ")
read_file.truncate(0)
write_file.close()
read_file.close()
def run(self):
empName = EmpInfoMerger()
thread1 = Thread(empName.write_to_temp_file("empName_file.txt","r"))
empAdd = EmpInfoMerger()
thread2 = Thread(empAdd.write_to_temp_file("empaddress.txt","r"))
output = EmpInfoMerger()
thread3 = Thread(output.write_to_file("output_file.txt", "w"))
thread1.start()
thread2.start()
thread3.start()
thread1.join()
# sleep(1)
thread2.join()
# sleep(1)
thread3.join()
obj = EmpInfoMerger()
obj.run()
我的输出:
Jhon Pitroda
Rinkal
Mumbai
Hubli
解决方案
您的write_to_temp_file()
功能似乎导致了问题。由于您有 2 个线程试图写入同一个文件,因此我认为会发生什么:thread1
并thread2
从他们给定的文件中读取并尝试写入temp_file.txt
. 但这里是交易,因为程序是线程的,文件的输出将取决于哪个线程在哪个时间运行。这意味着线程的调度将改变文件的输出。如果要将一个文件附加到另一个文件,则应避免使用线程。您应该在单个线程中运行这些操作,而不是线程运行此操作,这将保证您的预期输出。此外,如果您希望线程一行接一行地写入文件,您可能需要使用事件. 这样,您的线程将相互发出信号,因此它们将始终具有确切的执行顺序。
推荐阅读
- angular - 无法以角度 ReactiveForm 获取 FormArray 结构
- ios - 在 SwiftUI 中设置视图的 ViewModel 的最佳方法是什么
- numpy - 使用 MeshLab 或其他可视化工具可视化以 npy 格式保存的 3D 网格
- ios - AudioKit 如何处理或重用 AKNodeRecorder
- vbscript - 从 Windows 资源管理器上下文菜单调用 VBScript
- excel - 在 Excel VBA 中使用 Outlook 控件
- database - 将保存的查询拉入元数据库
- sql - 将 XML 文件导入 SQL Server 表时遇到问题
- python - 如何使用 try 块来捕获文件中没有足够的元素
- python - 是否可以解决 BrokenPipeError: [Errno 32] Broken pipe in LDA 模型?