执行re.sub后导出到CSV文件

时间:2018-06-12 18:17:01

标签: regex csv export-to-csv

我写了一个代码来在csv文件中进行替换。代码工作,我得到了结果:

import re
with open('c:\\users\\Mehrdad\\Desktop\\file.csv','r') as f:
    contents = f.read()
sub = re.sub(r"(\w+) (\d+) - (Present)" ,r"\1, \2, 2018", contents)
print (sub)

现在,我想将结果导出为CSV文件,但我尝试了很多命令,但仍然没有答案!有谁知道我应该使用什么命令来导出结果?

1 个答案:

答案 0 :(得分:1)

您可以尝试这样的事情:

import re
with open('c:\\users\\Mehrdad\\Desktop\\file.csv','r') as f, open('output_file_name.csv', 'w') as out:
    contents = f.read()
    sub = re.sub(r"(\w+) (\d+) - (Present)" ,r"\1, \2, 2018", contents)
    out.write(sub)
print (sub)