如何将打印输出保存到Excel表格中

2024-09-22 20:18:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个脚本,可以分析来自PLC的标签 读了一堆标签,读了很多 我想知道如何将打印输出保存到excel文件中,但使用表格格式

这是脚本的一部分

with PLC() as comm:
    comm.IPAddress = '192.168.100.5'
    comm.ProcessorSlot = 0
    ret = comm.GetPLCTime()

    print("Fecha y Hora de Registro Revision Fallas", ret.Value)
    time.sleep(1)
    Estacion = "D2M017"

   #ACTUADOR 1 
   ACTUADOR = comm.Read('D2M_017.Status.Act._1.WBypassed')
   ret = comm.GetPLCTime()
   Numero_Act_EnBypass = 0
   if ACTUADOR.Value == True:
        Sensor = "ACTUADOR 1 WORK SENSOR EN BY PASS"
        Numero_Act_EnBypass = (Numero_Act_EnBypass +1)
       print(Estacion, ret.Value, "D2M017 =",Sensor)
   else:
        Sensor = "ACTUADOR 1 WORK OK"



   ACTUADOR = comm.Read('D2M_017.Status.Act._1.HBypassed')
   ret = comm.GetPLCTime()
   if ACTUADOR.Value == True:
        Sensor = "ACTUADOR 1 HOME SENSOR EN BY PASS"
        Numero_Act_EnBypass = (Numero_Act_EnBypass +1)
        print(Estacion, ret.Value, "D2M017 =",Sensor)
   else:
        Sensor = "ACTUADOR 1 HOME OK"

这部分重复64次以上 最后我得到了这个结果

Result of Program

我需要将这些信息保存到excel的表格中 四分五裂 成立、日期、状态


Tags: 脚本value标签sensoractplccommprint
2条回答

你看过熊猫吗?它有很多强大的表格功能,包括直接导出到excel。下面是我的简单代码,希望有用

import pandas as pd
plc_data = pd.DataFrame(columns=['Tag', 'DateTime', 'Actuator', 'Value'], dtype=object)
# Code to get tags e.g.:
for i in range(10):
    # This is just a loop to generate data. In your case put your code to extract data correctly
    plc_tag = 'XXX_{0}'.format(i)
    date_time = '2019-06-{0}'.format(i+5)
    actuator = 'ACTUADOR {0}'.format(i)
    act_value = 'Work Ok'
    temp_dict = {'Tag': plc_tag, 'DateTime': date_time, 'Actuator': actuator, 'Value': act_value}
    plc_data = plc_data.append(temp_dict.copy(), ignore_index=True)     # I have used a copy of the dictionary, although I'm not sure it's fully necessary. 

plc_data.to_excel("output.xlsx", sheet_name='Sheet_name_1', index=False)

有几种方法可以解决这个问题:最简单的方法是使用csv编写器,并将其写入文件,而不是打印到控制台

以您的代码为基础:看起来可能是这样的

import csv

with PLC() as comm:
    with open("output_file.csv",'w') as f:
    csv_writer = csv.writer(f, delimiter=',')
...   
#ACTUADOR 1 
   ACTUADOR = comm.Read('D2M_017.Status.Act._1.WBypassed')
   ret = comm.GetPLCTime()
   Numero_Act_EnBypass = 0
   if ACTUADOR.Value == True:
        Sensor = "ACTUADOR 1 WORK SENSOR EN BY PASS"
        Numero_Act_EnBypass = (Numero_Act_EnBypass +1)
        print(Estacion, ret.Value, "D2M017 =",Sensor)
   else:
        Sensor = "ACTUADOR 1 WORK OK"
   csv_writer.writerow([Estacion, ret.Value,f"D2M017 = {Sensor}"])
   ...

如果您确实需要写入excel(.xsl或.xslx)文件,那么有几个包可用:xslxwriter可能是最容易使用的包之一https://xlsxwriter.readthedocs.io/

最后:如果要将任何终端命令的输出保存到文件中,可以“管道”将其输出

在windows和linux中,这看起来像:python_script.py>;myoutputfile.txt

相关问题 更多 >