gpt4 book ai didi

Python 3 csv.reader 空响应

转载 作者:行者123 更新时间:2023-12-01 03:49:55 26 4
gpt4 key购买 nike

您好,我收到以下代码,但循环无法工作,因为 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:我对Python完全是菜鸟。

最佳答案

你的list(reader)调用消耗了reader,它在for循环中是空的。

直接替换即可

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

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

关于Python 3 csv.reader 空响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38415577/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com