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

问题描述 投票:1回答:1

我有两个无线电,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中......我想要有两个不同的CSV,这就是为什么我把时间戳放在CSV名称中,我还需要记录任何迭代的数据。有关如何解决此问题的任何想法?谢谢!

python multithreading csv threadpool python-multithreading
1个回答
1
投票

您在同一天和同一小时和分钟打开outfile,因此您在两个作业中写入同一文件,只需使该函数使用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:
                ...

然后使用包装器在将qizxswpoi映射到线程池中时将其从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()
© www.soinside.com 2019 - 2024. All rights reserved.