TypeError:“发电机"对象不可下标,CSV文件 [英] TypeError: 'generator' object is not subscriptable, csv file

查看:152
本文介绍了TypeError:“发电机"对象不可下标,CSV文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了typeerror:当尝试在多个csv文件中列出信息列表,对其进行排序时,"generator"对象无法下标,以便获得所需的信息并将该信息放入新的.xlsx文件中.我想知道这里是否有人可以帮助我解决我的问题所在.是无法访问的csv文件,还是我的代码有问题? (我没有添加整个代码,仅添加了出现错误的代码)

I am getting the typeerror: 'generator' object is not subscriptable when trying to make lists of information in several csv files, sort them so that I get the information I need and put that information into a new .xlsx file. I am wondering if anyone here can help me with where I am going wrong. Is it the csv files that cannot be accessed or is there something wrong with my code? (I did not add the entire code, only the code where I get the error)

代码:

import csv
import operator
from openpyxl import Workbook, load_workbook
import os
import logging

def opencsv(csvfile):
    csvdata = []
    with open(csvfile, encoding='utf-8-sig') as csv_input:
        try:
            reader = csv.reader(csv_input, delimiter=';')
            for row in reader:
                key_1 = row[0]
                key_2 = row[1]
                1_2 = key_1.split(';')
                2_1 = key_2.split(';')


                csvdata.append(list+link)
                sortedlist = sorted(csvdata, key=operator.itemgetter(0), 
                reverse=False)
        return sortedlist
    finally:
        csv_input.close()

def copycsv(excel_file, csvfile):
    rel_path_xlsx = r'C:\Myfolder\xlsx'
rel_path_csv = r'C:\Myfolder\CSV'
wb1 = load_workbook(rel_path_xlsx+"\\"+excel_file)
wb2 = Workbook()
ws1 = wb1.active
ws2 = wb2.active

sortedlist = opencsv(rel_path_csv+"\\"+csvfile)
listed = sorted(sortedlist, key=operator.itemgetter(0), reverse=False)
for info in listed:
    ws2.append(info)

col_v = ws2.columns[0] #line 39, error
col_n = ws2.columns[1] 

for idx, cell in enumerate(col_v, 1):
    ws1.cell(row=idx, column=4).value = cell.value

for idx, cell in enumerate(col_n, 1):
    ws1.cell(row=idx, column=5).value = cell.value

wb1.save(r"C:\Myfolder"+"\\"+"file_"+excel_file)


def copyxlsx(rel_path_xlsx, rel_path_csv):
    for filename in zip(sorted(os.listdir(rel_path_xlsx)), 
    sorted(os.listdir(rel_path_csv))):
    print(filename[0], filename[1])
    copycsv(filename[0], filename[1]) #line 55, error

Traceback (most recent call last):
line 55, in copyxlsx
   copycsv(filename[0], filename[1])
line 39, in copycsv
   col_v =ws2.columns[0]
TypeError: 'generator' object is not subscriptable

我对python还是很陌生,所以任何帮助将不胜感激!使用Python3.4.1

I am quite new to python, so any help will be highly appreciated! Working in Python3.4.1

推荐答案

worksheet.columns返回生成器(错误提示).您需要将其转换为可下标的对象(即列表或元组),以便按索引获取列:

worksheet.columns returns a generator (as the error suggests). You'll need to convert it to a subscriptable object (ie list or tuple) in order to get a column by index:

cols = tuple(ws2.columns)
col_v = cols[0]
col_n = cols[1] 

甚至更好,假设只有两列:

Or even better, assuming there are only 2 columns:

col_v, col_n = tuple(ws2.columns)

或者如果有多于2列,则您不需要关心其余的内容,而无需使用Python 3:

Or if there are more than 2 columns, you don't care about the rest and using Python 3:

col_v, col_n, *_ = tuple(ws2.columns)

请注意,这将在内存中创建一个无用的列表.您也可以做
col_v, col_n = tuple(ws2.columns)[:2]可在Python 2和3中使用,并且不会在内存中创建不必要的列表.

Note this will create a useless list in memory. You could also do
col_v, col_n = tuple(ws2.columns)[:2] that works in both Python 2 and 3, and won't create a needless list in memory.

这篇关于TypeError:“发电机"对象不可下标,CSV文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆