Python 将文本文件转换为csv格式

Python 将文本文件转换为csv格式,python,csv,if-statement,text,for-loop,Python,Csv,If Statement,Text,For Loop,原始文件格式如下所示 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,雾底,22201,H_街。 华盛顿特区,A9999,史密森尼特区,12345,第14街。 . . 我尝试使用if语

原始文件格式如下所示

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,雾底,22201,H_街。
华盛顿特区,A9999,史密森尼特区,12345,第14街。 . .

我尝试使用if语句和elif

if lines.find('ID'):
   lines[5:]
elif lines.find('SY'):
   lines[5:]
如果我用这种方法,每次只能得到一个值。 谁能给我推荐一下吗?
谢谢

假设原始文件中的数据是以制表符分隔的,您可以使用该模块,并执行以下操作:

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]]

原始文件,是制表符分隔的吗?原始文件是纯文本。