如何在从一个文件复制数据时将多线程转换为某个文件,然后将其粘贴到另一个文件中

时间:2016-11-18 12:03:01

标签: python multithreading python-2.7

问题我想使用线程将温度在C到F的txt doc(first.txt)转换为下面保存输出到另一个文件(second.txt)是我到目前为止但是,我无法为了让它正常工作任何帮助将不胜感激。

import os
import sys
from Queue import Queue
from threading import Thread


class ConverterWorker(Thread):
  def __init__(self, queue):
      Thread.__init__(self)
      self.queue = queue

  def run(self):
      while True:
        temps = self.queue.get()
        self.queue.task_done()



class copy_and_convert_temps(object):


  def run_it(self):
    copy_and_convert_temps().do_them_together()


  def do_them_together(self):
    first_txt = "first.txt"
    second_txt = "second_txt"
    queue = Queue()
    for x in range(2):
      worker = ConverterWorker(queue)
      worker.daemon = True
      worker.start()
      with open(first_txt, "r") as f1:
        with open(second_txt, "w") as f2:
          f_temps = f1.readlines()
          for xt in f_temps:
            ct = copy_and_convert_temps().convert_temps(xt)
            queue.put((ct))
          queue.join()
          f2.writelines(ct)


  def convert_temps(self, temp):
    for xi in temp:
      f_to_c = 9.0/5.0 * int(xi) + 32

      yield (str(f_to_c) + "\n")






copy_and_convert_temps().run_it()

第一个文字

2
12
-3
-10
5

第二个文字

   ^should have converted C temps to F 
   ?
   ?
   ?
   ?
   ?
   ?

0 个答案:

没有答案