2014-04-15 77 views
0

原始文件格式是这样转换文本文件转换成CSV格式

ID DC_trip 
AC A9999 
SY DC,Foggy_bottom,22201,H_St. 
SY DC,Smithsonian,12345,14th_St. 
// 
ID ... 
AC ... 
SY ... 
SY ... 
SY ... 

我想将其转换为.csv文件格式,并把它变成

DC_trip,A9999,DC,Foggy_bottom,22201 ,H_ST。
DC_trip,A9999,DC,Smithsonian,12345,14th_St。 。 。 。

我想如果我用这样的方式,每次我只能得到一个值if语句和elif的使用.....

if lines.find('ID'): 
    lines[5:] 
elif lines.find('SY'): 
    lines[5:] 

。 有人可以给我一些建议吗? 谢谢

+0

原始文件,它是制表符分隔吗? – shaktimaan

+0

原始文件是纯文本。 –

回答

0

假设在原文件中的数据是制表符分隔,可以使用csv模块,并做到这一点:

data = [] 
# Extract the second row from the input file 
# and store it in data 
with open('input') as in_file: 
    csv_reader = csv.reader(in_file, delimiter='\t') 
    for row in csv_reader: 
     data.append(row[1]) 

# The first two values in data is the suffix 
# for the rest of your output file 
suffix = ','.join(data[:2]) 

# Append the suffix to the rest of the values 
# and write it out to the output file. 
with open('output') as op_file: 
    for item in data[2:]: 
     op_file.write('{},{}\n'.format(suffix, item)) 

如果在原始文件中的数据由空格分隔,你会替换第一部分:

data = [] 
with open('file1') as in_file: 
    for line in in_file: 
     data.append(line.strip().split()) 
data = [a[1] for a in data if a[1]]