1

I am opening a .tsv file and changing its contents using some regexp:

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

How can I save the modified contents to another .tsv file?

Update: I need to save full line, not only line[2]

Contra111
  • 325
  • 2
  • 10

2 Answers2

0

I think that

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

should work, but I didn't test it.

Reference answer

Iulian Onofrei
  • 9,188
  • 10
  • 67
  • 113
0

You can do this using below code.

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])
DeshDeep Singh
  • 1,817
  • 2
  • 23
  • 43