无法小写csv文件的标题

时间:2017-10-23 21:30:56

标签: python csv lowercase

我正在尝试使用python在目录中的多个csv文件中创建第一行/标题小写。代码和错误如下。有没有办法修复代码或其他方式?

sonatype/nexus3

错误是:

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)

1 个答案:

答案 0 :(得分:0)

我认为你正在混淆行和列。这里有一些未经测试的代码可以做你想要的,我想:

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.