将文本文件转换为csv格式

2024-09-29 19:37:03 发布

您现在位置:Python中文网/ 问答频道 /正文

原始文件格式如下所示

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

我想将其转换为.csv文件格式并将其转换为

华盛顿特区,A9999,华盛顿特区,雾底,22201,H_St.
华盛顿特区,邮编:12345,14街,邮编:A9999。 . . . 在

我试着用if语句和elif。。。。。在

^{pr2}$

如果我用这种方法,每次只能得到一个值。 有人能给我推荐一下吗? 谢谢你


Tags: csvidif语句dcacsttrip
1条回答
网友
1楼 · 发布于 2024-09-29 19:37:03

假设原始文件中的数据是制表符分隔的,则可以使用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))

如果原始文件中的数据由空格分隔,则应将第一部分替换为:

^{pr2}$

相关问题 更多 >

    热门问题