如何将以下python输出结果保存为.csv格式

时间:2018-10-06 10:06:57

标签: python python-3.x csv

如何将这段代码的结果保存为.csv格式?

import re
import CSV

text = open('example.txt').read()
pattern = r'([0-9]+)[:]([0-9]+)[:](.*)'
regex = re.compile(pattern)
for match in regex.finditer(text):
      result = ("{},{}".format(match.group(2),match.group(3)))

1 个答案:

答案 0 :(得分:0)

如果我正确理解了您的问题,则可以按以下方式生成CSV:

import re

text = open('example.txt').read()
pattern = r'([0-9]+)[:]([0-9]+)[:](.*)'
regex = re.compile(pattern)
with open('csv_file.csv', 'w') as csv_file:
    # Add header row with two columns
    csv_file.write('{},{}\n'.format('Id', 'Tile'))
    for match in regex.finditer(text):
          result = ("{},{}".format(match.group(2),match.group(3)))
          csv_file.write('{}\n'.format(result))