Replace the delimiter in a csv file using Python

Recently I had to wrangle some csv files, including some data calculations and outputting a semi-colon delimited file instead of a comma-delimited file.

'''
@date 19/07/2016
@author Cindy Williams-Jayakumar
Replaces the delimiter in a csv file
using the pathlib library in Python 3
'''
import csv
from pathlib import Path
folder_in = Path(r'C:\Some\Arb\Folder\in')
folder_out = Path(r'C:\Some\Arb\Folder\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)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.