Search code examples
pythoncsvlowercase

Unable to lowercase the header of csv file


I'm trying to make the first row/header lowercase, in multiple csv files in a directory using python. The code and error are below. Is there any way to fix the code or some other way?

import csv
import glob

path = (r'C:\Users\Documents')

for fname in glob(path):
    with open(fname, newline='') as f:
        reader = csv.reader(f)
        row1 = next(reader)
        for row1 in reader:
            data = [row1.lower() for row1 in row1]
            os.rename(row1, data)

The error is:

TypeError: rename: src should be string, bytes or os.PathLike, not list

Solution

  • I think you're getting rows and columns mixed-up. Here's some untested code that does what you want, I think:

    import csv
    from glob import glob
    
    path = (r'C:\Users\Documents\*.csv')  # Note wildcard character added for glob().
    
    for fname in glob(path):
        with open(fname, newline='') as f:
            reader = csv.reader(f)
            header = next(reader)  # Get the header row.
            header = [column.lower() for column in header]  # Lowercase the headings.
            rows = [header] + list(reader)  # Read the rest of the rows.
    
        with open(fname, 'w', newline='') as f:
            writer = csv.writer(f)
            writer.writerows(rows)  # Write new header & original rows back to file.