如何在Python中同时编写两个CSV?
我有两个收音机,sdr和sdr2,接收数据,我想把日期(复数)保存在CSV文件中。我需要同时从两台收音机获取数据,在每台收音机上运行5次扫描,因此我在代码的主要部分所做的是:如何在Python中同时编写两个CSV?,python,multithreading,csv,threadpool,python-multithreading,Python,Multithreading,Csv,Threadpool,Python Multithreading,我有两个收音机,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.ma
#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名称中,并且我还需要记录任何迭代的数据。
你知道怎么解决这个问题吗?谢谢 您在同一天、同一小时、同一分钟内打开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从枚举
解包到无线电:
#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()
你能把文件名作为self的一个成员并写入那个csv文件吗?非常感谢!我只是不明白你把第二段代码放在哪里…这会放在类扫描中吗?而pool.map是在主扫描还是在类扫描中?因为我看不出你是如何从主界面调用扫描的。非常感谢。谢谢:)代码没有给出任何错误,但我只得到一个文件:“01.03.18-1043.csv_0”,当我将其编辑为“01.03.18-1043.csv”并打开它时,我看到了上一次迭代的示例,我想只有一个无线电…@联系我们落后科学,刚刚意识到您在当前时间格式中使用了“.csv”,现在应该正确地命名它。不管怎样,现在试着比较这两个文件,因为你应该得到2个文件,每个SDR一个,它现在工作:)非常感谢!!我试图提高你的回答,但我没有足够的声誉,所以我把它标记为答案:D