S
S
Sergey2020-09-25 13:28:46
Python
Sergey, 2020-09-25 13:28:46

I can't pass a string to writerow, what's wrong?

Console throws TypeError: string indices must be integers when trying to pass it line by line

for i in range(j, len(property)):
  k = j
  write_to_csv(property[k])
  k += 1
j = len(property)

Full error text:
Traceback (most recent call last):
File "C:/Users/Danis/PycharmProjects/parser/parser_cian.py", line 116, in
get_offices(url)
File "C:/Users/Danis/PycharmProjects/parser /parser_cian.py", line 71, in get_offices
write_to_csv(property[k])
File "C:/Users/Danis/PycharmProjects/parser/parser_cian.py", line 82, in write_to_csv
a_pan.writerow((building['address '], building['area'], building['price'], building['price per m²'],
TypeError: string indices must be integers

def write_to_csv(property):
    with open('cian_parser.csv', 'a', encoding='utf8', newline='') as file:
        a_pan = csv.writer(file, delimiter=',')
        for building in property:
            a_pan.writerow((building['адрес'], building['площадь'], building['цена'], building['цена за м²'],
                            building['ссылка'], building['дата выгрузки']))
    read_file = pd.read_csv(r'cian_parser.csv')
    read_file.to_excel(r'cian_parser.xlsx', index=None, header=True)

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sergey, 2020-09-28
@SITihomirov

Understood, the cycle was not needed.
We change

def write_to_csv(property):
    with open('cian_parser.csv', 'a', encoding='utf8', newline='') as file:
     #...

on the
def write_to_csv(property):
    with open('cian_parser.csv', 'w', encoding='utf8', newline='') as file:
    #...

S
Sergey Pankov, 2020-09-25
@trapwalker

This is a nightmare ... A
pile of some unnecessary squats and curtsies. There is a feeling. that the code was written without any understanding of what and how it works.
Here it is easier to count the lines that would not need to be corrected: zero such lines.
You would give at least an example of what you have there in the property served. And then, on the coffee grounds, you have to guess which of the hundreds of errors finally made the code inoperable.
Here is some nonsense in general:

for i in range(j, len(property)):
    k = j
    write_to_csv(property[k])
    k += 1
  j = len(property)

Okay, the trouble with indents. But why these meaningless assignments? Why this meaningless loop if you process the same element many times in it?
Stop writing this already. There is no point. Not yours.
It looks like (thick stains suggest this for lack of other data) you do not understand what you are passing into this function of yours. The situation would be clarified by the publication of the contents of the variable roperty

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question