在python第2部分中将csv文件转换为管道分隔文件

时间:2016-02-11 17:35:44

标签: python csv

我使用python3将一些文件从逗号转换为|定界符

马丁诺一年前就这个话题给出了一个非常有用的答案 Convert csv file to pipe delimited file in python

但是,如果我将文件格式从 rb 更改为 rt

,它只适用于我

我的代码如下

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)

问题它坚持在每行之后添加额外的换行符。有没有办法避免这种情况?

示例输入文件: sample input file

0 个答案:

没有答案