Python CSV更改分隔符 [英] Python CSV change separator

查看:475
本文介绍了Python CSV更改分隔符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于一个研究项目,我有很多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.

我通常在Excel中执行此操作,但这需要大量工作。而且我需要分别为每个文件执行此操作,而Excel需要大量时间来执行此操作。

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:


  1. 逗号不会以分号更改。

  2. ,由于某种原因,它添加了一个空白行,我不知道为什么会这样做。

有人可以给一些提示吗?

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)


推荐答案

没有答案,这是我对同一文件中以逗号分隔的csv逗号分隔的建议:

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.

如果您不需要更改在同一文件中,您可以选中 answer

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

这篇关于Python CSV更改分隔符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆