最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

python - How do I change the case using csv - Stack Overflow

programmeradmin3浏览0评论

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.

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.

Share Improve this question edited Feb 16 at 12:17 Mark Rotteveel 109k227 gold badges156 silver badges220 bronze badges asked Feb 16 at 11:23 Erandel ElvanErandel Elvan 154 bronze badges 2
  • 1 Why is your code reading two files? – no comment Commented Feb 16 at 11:27
  • I was given this task – Erandel Elvan Commented Feb 16 at 11:39
Add a comment  | 

1 Answer 1

Reset to default 4

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)
发布评论

评论列表(0)

  1. 暂无评论