如何在Python中同时写入两个CSV?

How to write two CSV concurrently in Python?

我有两个收音机,sdr 和 sdr2,正在接收数据,我想将该日期(复数)保存在 CSV 文件中。我需要同时从两个收音机获取数据,运行 每个扫描 5 次,所以我在代码的主要部分所做的是:

#we save the sdr and sdr2 in the same array
radios = [ sdr, sdr2]
pool = ThreadPool(4)
#create an object of class Scan
s=Scan()
#pool.map(function, array)
pool.map(s.scan, radios)
pool.close() 
pool.join()

那么,扫描函数为:

class Scan: 
    def scan(self, object):   
      for i in range(0,1):
        #Read iq data
        samples = object.read_samples(256*1024)
        #print(samples)

       #get the maximum amplitude in frequency to save IQ samples if it's greater
       #than -1 dB
        sp = np.fft.fft(samples)
        ps_real=sp.real
        ps_imag=sp.imag
        sq=np.power(ps_real,2)+np.power(ps_imag,2)
        sqrt=np.sqrt(sq)
        psd=sqrt/1024
        value=[ps_real,ps_imag]
        max=np.max(psd)
        log=10*math.log10(max)
        print(value)
        current_time = time.strftime("%m.%d.%y-%H%M.csv", time.localtime())
        if log > -1:
            #save the IQ data in csv
            with open('%s' % current_time, 'w',newline='') as f:
                writer = csv.writer(f, delimiter=',')
                writer.writerows(zip(ps_real,ps_imag))

但是这样做是从其中一个收音机的最后一次迭代中获取数组(真实的,想象的对)(我认为它只是一个)并将其保存在一个独特的 CSV 中......我想有 2 个不同的 CSV,这就是为什么我将时间戳放在 CSV 名称中,我还需要记录任何迭代的数据。 关于如何解决这个问题的任何想法?谢谢!

您在同一天、同一小时和同一分钟打开输出文件,因此您在两个作业中写入同一个文件,只需让该函数使用一个 id 并将其作为参数传递即可:

class Scan: 
    def scan(self, id, object):
        ...
        current_time = time.strftime("%m.%d.%y-%H%M", time.localtime())
        if log > -1:
            #save the IQ data in csv
            with open('{}_{}.csv' .format(current_time, id), 'w',newline='') as f:
                ...

然后在线程池中映射它时,使用包装器将 id 从 enumerate 解压缩到无线电:

#we save the sdr and sdr2 in the same array
radios = [ sdr, sdr2]
pool = ThreadPool(4)
#create an object of class Scan
s=Scan()

def scan(args_tuple):
    global s
    id, code = args_tuple
    return s.scan(id, code)

pool.map(scan, enumerate(radios))
pool.close() 
pool.join()