Python Programming help

If you can help me, I would greatly appreciate it

When running the code, it works well, but it duplicates the information from the other columns. I want to create new lines in all columns and fill only the line of a specific column by splitting the text separated by pipes (‘|’). The issue is that the code duplicates the information from the other columns when splitting the text that was supposed to be blank. If you can help me, I would greatly appreciate it.

There are 14 columns
python

import csv

Function to split data into rows with information before and after “|”

def split_lines(input_file, output_file):
with open(input_file, ‘r’, newline=‘’) as csvfile, open(output_file, ‘w’, newline=‘’) as outputcsv:
reader = csv.reader(csvfile, delimiter=‘;’)
writer = csv.writer(outputcsv, delimiter=‘;’)

    for row in reader:
        for i, cell in enumerate(row):
            parts = cell.split('|')
            if len(parts) > 1:
                for j in range(len(parts) - 1):
                    # Append the split information to the current cell
                    row[i] = parts[j]
                    # Write the current row with the added information
                    writer.writerow(row)
                # Update the current cell with the remaining part
                row[i] = parts[-1]

        # Write the current row after all the splits
        writer.writerow(row)

Input and output CSV file names

input_file = ‘o.csv’
output_file = ‘setembro1000.csv’

Call the function to split the data and write the result to the new file

split_lines(input_file, output_file)

my goal is here
the “input” is the data before

2 Likes
for row in reader:
    parts = row.split(';')  # Split the line into columns
    last_column = parts[-1].split('|')  # Split the last column on pipe character
    base_parts = parts[:-1]  # All columns except the last one

    # Write out each item from the last column as a new line
    for item in last_column:
        new_line = ';'.join(base_parts + [item]) + '\n'
        writer.writerow(new_line)

I haven’t tested this, but hope it helps

I haven’t managed to do it yet, but you’ve helped. Thank you

1 Like