open a csv file, split the third column into multiple 25 row columns, save the modification, and then iterate over all csv files in a folder in python

You can open a CSV file in Python using the csv module. To split the third column into multiple 25-row columns, you can use string and list manipulation techniques. Here's an example code snippet:

main.py
import csv
import os

# Function to split a list into chunks of size n
def chunks(lst, n):
    for i in range(0, len(lst), n):
        yield lst[i:i + n]

# Function to process a CSV file
def process_csv(file_path):
    with open(file_path, 'r') as file:
        reader = csv.reader(file)
        rows = list(reader)
    
    # Split the third column into 25-row columns
    column_values = [row[2] for row in rows]
    column_chunks = list(chunks(column_values, 25))
    
    # Insert the new columns into the rows
    for i, chunk in enumerate(column_chunks):
        for j in range(len(rows)):
            rows[j].insert(2 + i, chunk[j])
    
    with open(file_path, 'w', newline='') as file:
        writer = csv.writer(file)
        writer.writerows(rows)

# Iterate over all csv files in a folder
folder_path = '/path/to/folder/'
for file_name in os.listdir(folder_path):
    if file_name.endswith('.csv'):
        file_path = os.path.join(folder_path, file_name)
        process_csv(file_path)
1002 chars
34 lines

This code defines a function process_csv that takes a file path as input and performs the required modifications on the CSV file. It uses the chunks generator function to split the third column into 25-row columns. Then, it inserts these new columns into the rows of the CSV file. Finally, it saves the modifications using the same file path.

The code then iterates over all the files in a folder (specified by folder_path) using the os.listdir function. It checks if each file has a ".csv" extension and passes its path to the process_csv function to process the file.

Make sure to replace '/path/to/folder/' with the actual path to the folder containing the CSV files in your system.

gistlibby LogSnag