使用列将文本文件转换为 CSV

Converting Text file to CSV with Columns

我正在尝试将文本文件转换为 CSV 文件以简化其他应用程序的工作流程。我遇到的问题是提供的文本文件在文件中有过量的 space,并且在使用 pandas 导出到 CSV 时读入一列。我试过将列名指定为参数,但它不起作用。

文本文件是这样写的,

85350   5211 APPLE LN               O                                                                                                                                                                     
85805   201 ORANGE ST               I                                                                                                                                                                     
84412   1313 BANANA RD              I 

像这样导出成CSV,

85350 5211 APPLE LN O,
85805 201 ORANGE ST I,
84412 1313 BANANA RD I

我希望导出的 CSV 包含列并且看起来与此类似,列是数字地址 In_Out、

Number,Address,In_Out
85350,5211 APPLE LN,O
85805,201 ORANGE ST,I
84412,1313 BANANA RD,I
rows=[]
#Open csv module create the file to write it to etc etc etc
with open('file.txt') as f:
          row=[]
          for line in f.readlines():#gets each and every line from the file
      
               words=line.split()#splitting each word at space
               row=[words[0],f"{words[1]} {words[2]} {words[3]}",words[4]]
               rows.append(row)#appending to the rows list
csv.writerows(rows)

pandas有一个读取固定宽度文本文件的方法。如果推断列的默认值不正确,则有 additional parameters 指示列的宽度,但在这种情况下它有效:

import pandas as pd

df = pd.read_fwf('input.txt', header=None)
df.to_csv('output.csv', index=False, header=['Number','Address','In_Out'])

output.csv:

Number,Address,In_Out
85350,5211 APPLE LN,O
85805,201 ORANGE ST,I
84412,1313 BANANA RD,I

问题是你的文件有空格但是地址也有空格。但是第一列和最后一列没有,所以你可能可以这样做:

import sys
for line in sys.stdin:
    line = line.strip()
    left, right = line.split( ' ', 1 )
    mid, right = right.rsplit( ' ', 1 )
    print( ",".join( [left,mid,right] ) )

这会给你这个:

$ python test.py < data.file
85350,  5211 APPLE LN              ,O
85805,  201 ORANGE ST              ,I
84412,  1313 BANANA RD             ,I

但是您也可以尝试 pandas read_fwf,因为您的文件看起来是固定宽度的。

>>> a = pandas.read_fwf( 'data.file', widths=[8,28,1], names=('Zip','Address','Status') )
>>> a
     Zip         Address Status
0  85350   5211 APPLE LN      O
1  85805   201 ORANGE ST      I
2  84412  1313 BANANA RD      I