Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
312 views
in Technique[技术] by (71.8m points)

python - How to change the separator used in a CSV file?

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:

  1. the comma is not getting changed in a semicolon.
  2. 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:convertTrajectoryIn') 
folder_out = Path(r'C:convertTrajectoryOut')

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)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...