首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在Python中同时编写两个CSV?

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

Stack Overflow用户
提问于 2018-01-03 16:26:43
回答 1查看 191关注 0票数 1

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

代码语言:javascript
复制
#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()

然后,扫描函数为:

代码语言:javascript
复制
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名称中,并且我还需要记录任何迭代的数据。有什么办法解决这个问题吗?谢谢!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-01-03 16:36:07

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

代码语言:javascript
复制
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:
                ...

然后在线程池中进行映射时,使用包装器将in从enumerate解压到radios:

代码语言:javascript
复制
#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()
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/48073696

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档