edit csv files in a folder in python

To edit CSV files in a folder using Python, you can use the csv module and the os module. Here is an example of how you can do it:

main.py
import csv
import os

# Define the folder path where the CSV files are located
folder_path = '/path/to/folder'

# Iterate over each file in the folder
for filename in os.listdir(folder_path):
    if filename.endswith('.csv'):
        # Construct the full path of the file
        file_path = os.path.join(folder_path, filename)
        
        # Open the CSV file in read mode
        with open(file_path, 'r') as file:
            # Read the CSV file into a list of dictionaries
            csv_data = list(csv.DictReader(file))
        
        # Modify the data as needed
        for row in csv_data:
            row['column_name'] = 'new value'
        
        # Open the CSV file in write mode
        with open(file_path, 'w', newline='') as file:
            # Write the modified data back to the file
            writer = csv.DictWriter(file, fieldnames=csv_data[0].keys())
            writer.writeheader()
            writer.writerows(csv_data)
        
        print(f'File {filename} updated successfully.')
1021 chars
30 lines

Make sure to replace '/path/to/folder' with the actual path to your folder containing the CSV files. The code will iterate over each CSV file in the folder, read the file into a list of dictionaries, modify the data as required, and then write the modified data back to the file.

Note: This example assumes that each CSV file has a header row. If your CSV files don't have headers, you may need to make adjustments to the code accordingly.

related categories

gistlibby LogSnag