【问题标题】:read a csv file and translate it in uppercase and store it in another csv file with python?读取一个csv文件并将其翻译成大写并用python将其存储在另一个csv文件中?
【发布时间】:2017-11-28 07:52:43
【问题描述】:

我需要读取一个 csv 文件并将其翻译成大写并使用 python 将其存储在另一个 csv 文件中 我有这个代码:

import csv
with open('data_csv.csv', 'rb') as f:
    header = next(f).strip().split(',')
    reader = csv.DictReader((l.upper() for l in f), fieldnames=header)
    for line in reader:
        print  line
with open('test.csv', 'r') as f:
    for line in f:
        print line

但我找不到正确的结果

【问题讨论】:

  • 什么是适合您的“正确结果”?

标签: python python-2.7 csv uppercase


【解决方案1】:

您不需要单独阅读标题。如果您不向DictReader() 提供fieldnames 参数,则会自动 读取标头。接下来,不要打印您的行,您现在已经阅读了整个文件并删除了所有行。

在同一个with 语句中打开输入和输出文件,然后您可以直接将行写入输出。这里不需要使用csv模块,因为你不需要解析出行,然后再将行组成行。

只需遍历文件,将大写,然后写出结果:

with open('data_csv.csv', 'r') as input, open('test.csv', 'w') as output:
    output.writelines(line.upper() for line in input)

【讨论】:

  • thnx 但他给了我这个错误 Error: [Errno 2] No such file or directory: 'test.csv'
  • @kazz:啊,我的错。当然,应该打开输出文件进行写入。已更正。
  • @kazz:打开它是为了阅读,这要求文件存在。您在代码中犯了同样的错误。
猜你喜欢
  • 2019-10-05
  • 2019-01-11
  • 2017-08-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-01-07
相关资源
最近更新 更多