I
I
ibmwatson2020-04-25 08:55:31
Python
ibmwatson, 2020-04-25 08:55:31

Python how to remove row by csv module?

Hello everyone, I can’t figure it out and find a sensible answer on the Internet, please help))
There is a script that sends a line from a csv file to a Yandex translator, the task is as follows:
1. We took the line
2. We sent the entire line except for the first column to Me Translator
3. Received code 200 - if everything is ok, delete the line from the file that was taken and write the already translated one to a new file.
4. If you did not receive the code 200, the line was left in the file.
Everything works in principle, but there are restrictions on the api key, and when the api key is blocked (more than 1 million characters per day), the code will not be 200, and you don’t really want to lose lines, but manually checking it is quite cumbersome, because. a lot of lines.

Script available:

import requests
import time
import csv

def main():
    spamReader = csv.reader(open('text.csv', encoding="utf-8", newline=''), delimiter=',')
    for row in spamReader:
        my_text = row[1:]
        old = row[0]

        # Отправка запроса в Яндекс переводчик
        time.sleep(2)
        s = requests.Session()
        url = 'https://translate.yandex.net/api/v1.5/tr.json/translate'

        from_data = {
            'lang': 'th-ru',
            'key': 'API ключ__Бесплатный в яндексе',
            'text': my_text
        }

        answ = s.post(url, data=from_data)
        print(answ.json()) #{'code': 200, 'lang': 'th-ru', 'text': ['Результат перевода первого столбца', 'Результат перевода второго столбца']}


        if answ.json()['code'] == 200:
            result = answ.json()['text']
            result = [old] + result
            print(result)

            # Записываем результат в новый файл
            with open('result_file.csv', 'a', newline='', encoding="utf-8") as f:
                writer = csv.writer(f)
                writer.writerow(result)
                f.close()
        else:
            print('Необходимо поменять API ключ')


if __name__ == '__main__':
    main()

Answer the question

In order to leave comments, you need to log in

2 answer(s)
I
ibmwatson, 2020-04-25
@ibmwatson

Of course, there is only one thought, if the code is not 200, then we write it to a new file, but then it will have to go through all the remaining lines, and if there are more than one thousand of them?

else:
            print('Необходимо поменять API ключ')
            with open('bad_result_file.csv', 'a', newline='', encoding="utf-8") as f:
                writer = csv.writer(f)
                writer.writerow(row)
                f.close()

D
Dimonchik, 2020-04-25
@dimonchik2013

the thought is completely correct
, write in sql , then separate the untranslated ones with a sql query

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question