【问题标题】:Save formated contents of file to another file in Python将文件的格式化内容保存到Python中的另一个文件
【发布时间】:2020-02-11 02:28:33
【问题描述】:

我正在打开一个.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]

【问题讨论】:

  • 所以只需在其中使用另一个上下文管理器 - 这次打开 with open("test.tsv", "w") as f: 并写入它。
  • 另外,我认为你会想像\$ 一样逃避$

标签: python regex csv


【解决方案1】:

您可以使用下面的代码来做到这一点。

import csv

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

【讨论】:

    【解决方案2】:

    我认为

    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")
    

    应该可以,但我没有测试它。

    Reference answer

    【讨论】:

    • 我收到错误“write() 参数必须是 str,而不是列表”,我猜是因为 line 是一个列表
    • new_tsvfile.write("\t".join(line[2]) + "\n") 工作吗?
    猜你喜欢
    • 2021-09-02
    • 2020-07-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多