【问题标题】:Python 3 csv.reader empty responsePython 3 csv.reader 空响应
【发布时间】:2016-11-19 19:30:51
【问题描述】:

您好,我得到了以下代码,但循环不起作用,因为 csv.reader 为空。包含 csv 数据的文件已正确打开。

为了理解: var pokemon 可以是任何 pokemon 名称作为字符串。 bot、logger 和 event 是来自 Hangoutsbot 的变量。 所有需要的库都已加载。

代码:

def pkmn_translate(bot, event, pokemon):
    logger.info("translating pokemon name")
    url = "https://raw.githubusercontent.com/PokeAPI/pokeapi/master/data/v2/csv/pokemon_species_names.csv"
    request = urllib.request.Request(url, headers = {"User-agent":"Mozilla/5.0", "Accept-Charset":"utf-8"})
    try:
        data = urllib.request.urlopen(request)
        csv_data = data.read()
        csvstr = str(csv_data).strip("b'")
        lines = csvstr.split("\\n")
        f = open('{}/pokemon_species_names.csv'.format(os.path.dirname(os.path.realpath(__file__))), "w",encoding='utf8')
        for line in lines:
            f.write(line + "\n")
        f.close()
        logger.info("translating db saved")
    except urllib.error.URLError as e:
        logger.info("{}: Error: {}".format(event.user.full_name, json.loads(e.read().decode("utf8","ignore"))['detail']))
        yield from bot.coro_send_message(event.conv, "{}: Error: {}".format(event.user.full_name, json.loads(e.read().decode("utf8","ignore"))['detail']))
        return
    pokemon_id = "default"

    f = open('{}/pokemon_species_names.csv'.format(os.path.dirname(os.path.realpath(__file__))), 'r', encoding='utf8') # opens the csv file
    try:
        logger.info("DEBUG: openFile")

        #Quick and dirty fix because CSV File is very big
        maxInt = sys.maxsize
        decrement = True

        while decrement:
            # decrease the maxInt value by factor 10
            # as long as the OverflowError occurs.

            decrement = False
            try:
                csv.field_size_limit(maxInt)
            except OverflowError:
                maxInt = int(maxInt/10)
                decrement = True
        logger.info("DEBUG: maxInt = {}".format(maxInt))

        reader = csv.reader(f)
        rows = list(reader)
        for row in reader:
            logger.info("DEBUG: row = {}".format(row))
            for column in row:
                if pokemon == column:
                    #DEBUG
                    logger.info("Info: row =  {}".format(row))
                    #SET VAR
                    pokemon_id = rows[row][0]
                    #DEBUG
                    logger.info("Info: {}".format(pokemon_id))
                    bot.coro_send_message(event.conv, "Info: {}".format(pokemon_id))
                else:
                    logger.info("Error: Name not in File!")
                    bot.coro_send_message(event.conv, "Error: Name not in File!")
            else:
                logger.info("DEBUG: Loop exited")
        else:
            logger.info("DEBUG: Loop exited")
    except:
        logger.info("Debug: Some error")
    finally:
        f.close()      # closing
    logger.info("Debug func: PokemonID = {}".format(pokemon_id))
    yield from pokemon_id
    return pokemon_id

在 for 循环中,读取器变量中没有数据,因此失败。我不知道如何让 csv.reader 工作。 PS:我是python的菜鸟。

【问题讨论】:

  • 正如答案,读者已经被消费了。另外,pokemon_id = rows[row][0] 似乎没有多大意义。
  • pokemon_id = rows[row][0] 必须稍后修复 xD 我知道这还行不通,但那是因为行最初是其他的 ;)

标签: python python-3.x csv parsing for-loop


【解决方案1】:

您的 list(reader) 调用会消耗阅读器,而阅读器在 for 循环中是空的。

只是替换

    reader = csv.reader(f)
    rows = list(reader)
    for row in reader:

通过

    reader = csv.reader(f)
    rows = list(reader)
    for row in rows:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-08-09
    • 1970-01-01
    • 2015-07-06
    相关资源
    最近更新 更多