Search code examples
pythonpython-3.xcsv

How do I change the case using csv


It is necessary to change the case of the first column in the CSV file to lower case using the csv module by writing to the same file.

with open('D:\\folder\file1.csv', 'r') as file1_csv, open('D:\\folder\file2.csv', 'r') as file2_csv:
    file1_csv= csv.reader(file1_csv, delimiter=';')
    file2_csv= csv.reader(file2_csv, delimiter=';')

Is it possible to do this with a single command? Not using Pandas.


Solution

  • No, it's not possible. You have to read the data, manipulate the data, then save the data; you can't do this all in "one command."

    import csv
    
    
    file_path = 'D:\\folder\\file1.csv'
    
    with open(file=file_path, newline='', encoding='utf-8') as f:
        reader = csv.reader(f, delimiter=';')
        rows = [[row[0].lower()] + row[1:] for row in reader]
    
    with open(file=file_path, mode='w', newline='', encoding='utf-8') as f:
        writer = csv.writer(f, delimiter=';')
        writer.writerows(rows)