Почему python пропускает строки в csv файлах?
Я пытаюсь записать в excel таблицу данные, но python записавыет данные через строку, а не в каждую строку.
with open("all_categories_dict.json",encoding='utf-8') as file:
all_categories = json.load(file)
iteration_count = int(len(all_categories)) - 1
count = 0
print(f"всего итераций: {iteration_count}")
for category_name, category_href in all_categories.items():
rep = [",", " ", "-", "'"]
for item in rep:
if item in category_name:
category_name = category_name.replace(item, "_")
req = requests.get(url=category_href, headers=headers)
src = req.text
with open(f"data/{count}_{category_name}.html", "w", encoding='utf-8') as file:
file.write(src)
with open(f"data/{count}_{category_name}.html", encoding='utf-8') as file:
src = file.read()
soup = BeautifulSoup(src, "lxml")
# поверка страницы на наличие таблицы с продуктами
alert_block = soup.find(class_='uk-alert-danger')
if alert_block is not None:
continue
# собираем заголовки таблицы
table_head = soup.find(class_="mzr-tc-group-table").find("tr").find_all("th")
product = table_head[0].text
calories = table_head[1].text
proteins = table_head[2].text
fats = table_head[3].text
carbohydrates = table_head[4].text
with open(f"data/{count}_{category_name}.csv", "w", encoding="utf-8-sig") as file:
writer = csv.writer(file, delimiter=';')
writer.writerow(
(
product,
calories,
proteins,
fats,
carbohydrates
)
)
# собираем данные продуктов
products_data = soup.find(class_="mzr-tc-group-table").find("tbody").find_all("tr")
product_info = []
for item in products_data:
product_tds = item.find_all("td")
title = product_tds[0].find("a").text
calories = product_tds[1].text
proteins = product_tds[2].text
fats = product_tds[3].text
carbohydrates = product_tds[4].text
product_info.append(
{
"Title": title,
"Calories": calories,
"Proteins": proteins,
"Fats": fats,
"Carbohydrates": carbohydrates
}
)
with open(f"data/{count}_{category_name}.csv", "a", encoding="utf-8-sig") as file:
_writer = csv.writer(file, delimiter=';')
_writer.writerow(
(
title,
calories,
proteins,
fats,
carbohydrates
)
)
with open(f"data/{count}_{category_name}.json", "a", encoding="utf-8") as file:
json.dump(product_info, file, indent=4, ensure_ascii=False)
Результат выглядит так:
Ответы (1 шт):
Автор решения: Dmitry
→ Ссылка
Попробуйте так
with open(f"data/{count}_{category_name}.csv", "w", encoding="utf-8-sig", newline='') as file:
согласен с комментарием, исправил согласно @insolor
