首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >用于循环工作和读取数据,但没有对csv文件进行写入。

用于循环工作和读取数据,但没有对csv文件进行写入。
EN

Stack Overflow用户
提问于 2022-09-17 15:19:44
回答 2查看 52关注 0票数 1

运行此代码时,所有操作都正常,但是输出没有写入CSV文件。我的data.txt文件包含一些链接。

代码语言:javascript
复制
import csv
import requests
from recipe_scrapers import scrape_html
from csv import writer

with open('recipe.csv', 'w', encoding='utf8', newline='') as file:
    thewriter = writer(file)
    header = ['Title', 'Ingredients', 'Instructions', 'Nutrition_Facts', 'image', 'links']
    thewriter.writerow(header)

    with open('data.txt', 'r') as inf:
        for line in inf:
            html = requests.get(line).content
            scraper = scrape_html(html=html, org_url=line)
            thewriter.writerow([scraper.title(), scraper.ingredients(), scraper.instructions(), scraper.nutrients(), scraper.image(), scraper.links()])
EN

回答 2

Stack Overflow用户

发布于 2022-09-17 15:27:25

如果代码的缩进如您所示,您只会将头写入输出文件,循环输入,然后只尝试从最后一个刮板再写一行,但即使是在退出with块时输出文件被关闭之后。

将最后一行缩进与scraper = ...相同的级别,否则不可能正常工作。如下所示:

代码语言:javascript
复制
with open('recipe.csv', 'w', encoding='utf8', newline='') as file:
    thewriter = writer(file)
    ...

    with open('data.txt', 'r') as inf:
        for line in inf:
            html = requests.get(line).content
            scraper = scrape_html(html=html, org_url=line)
            thewriter.writerow([.....])     # <---- proper indent
票数 2
EN

Stack Overflow用户

发布于 2022-09-17 16:51:26

我会尝试重新安排逻辑,使之更有秩序。在将来调试代码时,这可能会有所帮助。

正如alexis所指出的,您的问题是不适当的缩进,导致了范围问题。我将重温您选择的一些关于Python范围的培训材料。

代码语言:javascript
复制
from csv import writer

import requests
from recipe_scrapers import scrape_html

with open('recipe.csv', 'w', encoding='utf8', newline='') as file:
    thewriter = writer(file)
    thewriter.writerow(['Title', 'Ingredients', 'Instructions', 'Nutrition_Facts', 'image', 'links'])  # Header
    
    with open('data.txt', 'r') as inf:
        for line in inf:
            html = requests.get(line).content
            scraper = scrape_html(html=html, org_url=line)
            
            thewriter.writerow([scraper.title(), scraper.ingredients(), scraper.instructions(), scraper.nutrients(), scraper.image(), scraper.links()])
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73756096

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档