Skip to content Skip to sidebar Skip to footer

Save The Same Content To .csv File As Print Command

Print command showing me something like this (I have more as 3 rows, but this is only part of example): O;4;Line[63];CPUA.DB1610.4122,X1;RW V;5;Enable_maintenance_mode;; V;5;Mainte

Solution 1:

The csv library is designed to take a list of column entries and convert it automatically into a whole csv row by adding the necessary delimiters for you. Your print statement is simulating this by appending the ; between each column entry. You can specify the delimiter to use when creating the csv.writer, in your example this is ;:

import csv

result = [
    ['V', '5', 'Enable_maintenance_mode', "S7:[CPUA]DB1610', 'X4124.0", 'B', 'RW', '0', "0']"],
    ['V', '5', 'Maintenance_start_motor', "S7:[CPUA]DB1610', 'X4124.1", 'B', 'RW', '0', "0']"],
    ['O', '4', 'Line[64]', '', '', "']"],
    ['V', '5', 'Enable_maintenance_mode', "S7:[CPUA]DB1610', 'X4126.0", 'B', 'RW', '0', "0']"]]

address = [
    "CPUA.DB1610.4122,X1;RW",
    "",
    "CPUA.DB1610.4124,X0;RW",
    "CPUA.DB1610.4124,X1;RW"]

withopen('output.csv', 'w', newline='') as f_output:
    csv_output = csv.writer(f_output, delimiter=';')

    for r, a inzip(result, address):
        csv_output.writerow(r[0:3] + a.split(';'))

When using a csv.writer() in Python 3.x, you should always open the file with w and set newline=''. Also it is easier to iterate through your result entries directly without using range() and indexing. As you appear to have two equal length lists, you can use zip to give you an element from each as you iterate.

This would give you an output file as follows:

V;5;Enable_maintenance_mode;CPUA.DB1610.4122,X1;RW
V;5;Maintenance_start_motor;
O;4;Line[64];CPUA.DB1610.4124,X0;RW
V;5;Enable_maintenance_mode;CPUA.DB1610.4124,X1;RW

Note, you have not provided a sample for address so this is based on your example output.

Post a Comment for "Save The Same Content To .csv File As Print Command"