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

2024-04-27 01:02:04 发布

您现在位置: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))

但是,这样做是得到数组(真实的,imag对)从最后一次迭代的一个收音机(我想它只是一个),并保存在一个独特的CSV…我想有两个不同的CSV,这就是为什么我把时间戳在CSV的名称,我还需要记录任何迭代的数据。 你知道怎么解决这个问题吗?谢谢!你知道吗


Tags: csvtheinobjecttimesavenpreal
1条回答
网友
1楼 · 发布于 2024-04-27 01:02:04

您在同一天、同一小时、同一分钟打开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:
                ...

然后在线程池中映射时,使用包装器将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()

相关问题 更多 >