python写csv文件分隔符问题,Python CSV更改分隔符

For a study project I have many many csv files that I need to change from comma (,) separated to semicolon (;) separated. So I only need to change the separator.

I normally do it in Excel, but that takes a lot of work. And there I need to do it for every file separately plus Excel take a lot of time to do it.

I have made a input and output folder.

That works fine in the code below.

The problem is:

the comma is not getting changed in a semicolon.

and for some reason it is adding a blank line, I don’t know why it does that.

Can somebody give some tips?

import csv

from pathlib import Path

folder_in = Path(r'C:\convert\Trajectory\In')

folder_out = Path(r'C:\convert\Trajectory\Out')

for incsv in folder_in.iterdir():

outcsv = folder_out.joinpath(incsv.name)

with open(str(incsv), 'r') as fin, open(str(outcsv), 'w') as fout:

reader = csv.DictReader(fin)

writer = csv.DictWriter(fout, reader.fieldnames, delimiter=';')

writer.writeheader()

writer.writerows(reader)

解决方案

There are no answer, here is my proposition for a csv comma to semicolon implementation on the same file:

path="file_to_convert.csv"

reader = list(csv.reader(open(path, "rU"), delimiter=','))

writer = csv.writer(open(path, 'w'), delimiter=';')

writer.writerows(row for row in reader)

I used the list() so the content of reader is kept and I reopen the file to write in it.

If you don't need the change to be in the same file you can check this answer.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值