Python 3 csv.reader空响应

时间:2016-07-16 21:00:13

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

您好我得到了以下代码,但循环无法正常工作,因为csv.reader为空。带有csv数据的文件正确打开。

了解:     var pokemon可以是任何口袋妖怪名称作为字符串。     机器人,记录器和事件是来自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循环中,它在reader变量中没有数据而且失败了。我不知道如何让csv.reader工作。 PS:我是蟒蛇的总菜鸟。

1 个答案:

答案 0 :(得分:2)

您的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: