首页 > 解决方案 > 将文件的格式化内容保存到Python中的另一个文件

问题描述

我正在打开一个.tsv文件并使用一些正则表达式更改其内容:

with open("test.tsv") as tsvfile:
    tsvreader = csv.reader(tsvfile, delimiter="\t")
    for line in tsvreader:
        #print(line[2])
        match = re.search('(\w*[А-Я]\w*[А-Я]\w*)|(\d)|(%|$|€)', line[2])
        if match:
            print(line[2])

如何将修改后的内容保存到另一个.tsv文件?

更新:我需要保存整行,而不仅仅是行 [2]

标签: pythonregexcsv

解决方案


我觉得

with open("test.tsv") as tsvfile, open("new_test.tsv", "a") as new_tsvfile:
    tsvreader = csv.reader(tsvfile, delimiter="\t")
    for line in tsvreader:
        #print(line[2])
        match = re.search('(\w*[А-Я]\w*[А-Я]\w*)|(\d)|(%|$|€)', line[2])
        if match:
            new_tsvfile.write(line[2] + "\n")

应该工作,但我没有测试它。

参考答案


推荐阅读