【问题标题】:Unable to lowercase the header of csv file无法小写 csv 文件的标题
【发布时间】:2017-10-23 21:30:55
【问题描述】:

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

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)

错误是:

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

【问题讨论】:

  • 首先,这可能会导致问题:for row1 in row1?
  • os.rename 用于重命名文件。您似乎想要执行小写,例如row1 = [entry.lower() for entry in row1],然后将新的 CSV 表写回磁盘。

标签: python csv lowercase


【解决方案1】:

我认为您混淆了行和列。我认为这是一些未经测试的代码,可以满足您的需求:

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.

【讨论】:

  • 非常感谢。除了在两个地方对代码进行少量更改之外,这很有效
  • subash707:很高兴听到这个消息。我只看到一个问题并解决了它。另一个是什么?无论如何,请考虑接受我的回答。见What should I do when someone answers my question?
  • glob.glob(path) 因为它抛出错误 TypeError: 'module' object is not callable and other [row for row in reader ] 代替 reader。
  • 谢谢。认为我在最新更新中都修复了它们。
猜你喜欢
  • 2014-08-21
  • 1970-01-01
  • 2018-03-21
  • 1970-01-01
  • 2017-04-16
  • 1970-01-01
  • 2018-03-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多