双API数据写入CSV时行拆分问题,求合并为单行的解决方案
解决CSV中API数据跨行列展示的问题
咱们先直接定位问题核心:你现在的代码里,把第一个API拿到的设备基础数据(myData)和第二个API拿到的子设备数据(myData2)分别调用了writer.writerow(),这就导致两组数据被写入CSV的两行,而不是你期望的同一行。
核心修复方案
你需要把两组数据合并成一个完整的列表,再一次性写入一行。修改代码中的循环逻辑部分即可:
# Loop to collect device name and status 500 at a time and print all 2080 in the file specified above. for x in range(5): string1 = "https://api.raincloud.com/rest/device?networkName=Company&take=500&skip="+str(x*500) response = requests.get(string1,headers=headers).json() for y in range (len(response)): myData = [(response[y]['device']),(response[y]['status'])] string2= 'https://api.raincloud.com/rest/device/'+str(myData[0])+'/subdevice' response2 = requests.get(string2,headers=headers).json() for z in range (len(response2)): # 合并设备数据和子设备数据,只取你需要的Model、StatusSub字段 myData2 = [(response2[z]['model']),(response2[z]['status'])] # 合并成一行所需的完整数据列表 combined_row = myData + myData2 # 如果需要加入时间戳,改成:combined_row = myData + myData2 + [datetime.datetime.now()] writer.writerow(combined_row)
额外优化建议(避免其他潜在问题)
- 避免重复写入表头:你当前的代码每次循环都会写入表头和空行,会导致CSV里重复出现表头。建议把表头写入逻辑只放在新建文件时:
if os.path.exists(today + '.csv'):#Create new file if its a new day Append_write = 'ab' else: Append_write = 'wb' with open(today + '.csv',Append_write) as myFile:#open todays csv file, set to write. writer = csv.writer(myFile) # 仅当新建文件时写入表头和空行 if Append_write == 'wb': writer.writerow(name) writer.writerow(space) # 后续的数据采集循环放在这里
- 修复定时逻辑:你当前
while True里的条件if datetime.datetime.now().minute % 15 == 0 or True等价于永远执行,起不到每15分钟运行一次的效果。可以改成更合理的定时逻辑:
import time while True: current_minute = datetime.datetime.now().minute if current_minute % 15 == 0: print(datetime.datetime.now()) # 执行你的数据采集和写入逻辑 # 等待1分钟,避免同一分钟内重复触发 time.sleep(60) else: # 没到时间就短暂休眠,减少CPU占用 time.sleep(10)
这样修改后,CSV里就能把设备信息和对应的子设备信息放在同一行,完全符合你期望的格式。
内容的提问来源于stack exchange,提问作者Daftyler
相关产品推荐
相关产品推荐

