1

I am using python3 to convert a number of files from comma to | delimiter

martineau gave a very helpful answer on this topic a year ago Convert csv file to pipe delimited file in python

however, it would only work for me if i changed the file fromat from rb to rt

my code is as follows

import csv
from os import listdir
from os.path import isfile, join

z= '\\'
path = r"C:\x milestone" + z
ipath = path+ r"toconvert" +z
opath = path + r'converted' +z

onlyfiles = [f for f in listdir(ipath) if isfile(join(ipath, f))] #list of files in ipath

for each in onlyfiles:    
  with open( ipath + each, 'rt') as inFile: 
      with  open(opath+ each, 'w') as outFile:
        reader = csv.DictReader(inFile)
        writer = csv.DictWriter(outFile, reader.fieldnames, delimiter='|')
        writer.writeheader()
        writer.writerows(reader)

question it insists on adding an extra linefeed after each line. is there a way to avoid this?


Sample input file: sample input file

Community
  • 1
  • 1
Lcat
  • 857
  • 1
  • 8
  • 16
  • There's many ways of doing this. But you should provide more details in your question. Add your current code. And which python version are you using? In python 3.x bytes and strings are different from python 2.7. – Håken Lid Feb 11 '16 at 17:41
  • This is not the most efficient way to do the conversion but it doesn't write extra lines for a normal csv file. Maybe your csv has odd line endings. Can you give us an example input file that produces the problem? – tdelaney Feb 11 '16 at 18:16

0 Answers0