将结构化文本文件转换为CSV

时间:2019-02-07 19:20:48

标签: python string split

如何在python中实现以下输出:

输入:

Prataps Peter A         A    T         9945.03  
Shailin Amy             B              9437.50  

输出:

Prataps,Peter,A,A,T,9945.03  
Shailin,Amy,,B,,9437.50

我正在使用的代码:

    input = "C:\Apps\Data\Report\CC_report.csv"
    final = "C:\Apps\Data\Report\CC_report1.csv"
    header = "LastName,FirstName,Middle_Name ,ST,B1,CURRENT_BALANCE)
    with open(input) as oldfile, open(final, 'w') as newfile:
        newfile.write(header+"\n")
        for line in oldfile:
           line1 = re.sub(" +", ",", line.strip())
           newfile.write(line1 + "\n")

2 个答案:

答案 0 :(得分:0)

从给定的输入中,我可以看到字段之间用空格分隔,因此您必须用逗号替换它们

file = open('data.txt', 'r')
data=myfile.read().replace(' ', ',')

一旦检索到内容,您可以将其添加到新文件中

new_file = open("data.csv", "w")
new_file.write(data)
new_file.close()

答案 1 :(得分:0)

我使用Numpy定义列宽。在处理文件之前,需要清除和定义数据。

var url = $('.urlPasar').data('request-url');
window.open(url, "_blank");