简体   繁体   English

TypeError:“发电机”对象不可下标,CSV文件

[英]TypeError: 'generator' object is not subscriptable, csv file

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. 我收到类型错误:尝试在多个csv文件中列出信息列表,对其进行排序时,“生成器”对象无法下标,以便我得到所需的信息并将该信息放入新的.xlsx文件中。 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? 是无法访问的csv文件,还是我的代码有问题? (I did not add the entire code, only the code where I get the error) (我没有添加整个代码,仅添加了我得到错误的代码)

Code: 码:

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

I am quite new to python, so any help will be highly appreciated! 我对python很陌生,因此任何帮助将不胜感激! Working in Python3.4.1 使用Python3.4.1

worksheet.columns returns a generator (as the error suggests). worksheet.columns返回一个生成器(错误提示)。 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)

Or if there are more than 2 columns, you don't care about the rest and using Python 3: 或者,如果有多于2列,则您无需理会其余部分,而无需使用Python 3:

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

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. col_v, col_n = tuple(ws2.columns)[:2]在Python 2和3中都可以使用,并且不会在内存中创建不必要的列表。

You're calling columns method on ws2, which returns a generator rather than a list. 您正在ws2上调用columns方法,该方法返回一个生成器而不是一个列表。 You cannot access generator's values using index, so you have two options: 您无法使用索引访问生成器的值,因此有两个选择:

1) read all values from a generator at once and create a list of them, then operate on the list: 1)一次从生成器中读取所有值并创建它们的列表,然后在该列表上进行操作:

column_list = list(ws2.columns)
col_v = column_list[0]
col_n = column_list[1]

2) read only the first two values using next function: 2)使用next函数仅读取前两个值:

col_v = next(ws2.columns)
col_n = next(ws2.columns)

Method 2 is preferable if your generator returns a long sequence of items, so you don't want to create a memory-hogging list of all of them. 如果生成器返回一长串项目,则最好使用方法2,因此您不想创建所有这些项目的内存消耗列表。 In your case, it probably doesn't matter. 就您而言,这可能并不重要。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Python'TypeError':'Generator'对象不可下标 - Python 'TypeError': 'Generator' object is not subscriptable 类型错误:“生成器”对象不可下标错误 - TypeError: 'generator' object is not subscriptable error python3:TypeError:'generator' object 不可下标 - python3: TypeError: 'generator' object is not subscriptable 类型错误:“设置”对象不可下标。 3 个 CSV 文件 - TypeError: 'set' object is not subscriptable. 3 CSV files TypeError:“ _ csv.reader”对象不可下标 - TypeError: '_csv.reader' object is not subscriptable openpyxl遍历列=> TypeError的单元格:'generator'对象不可下标 - openpyxl iterate through cells of column => TypeError: 'generator' object is not subscriptable for ws.rows [1:]中的行:TypeError:'generator'对象不可下标 - for row in ws.rows[1:]: TypeError: 'generator' object is not subscriptable 从Python 2.7切换到3.7错误:“ TypeError:'generator'对象不可下标” - Switching from Python 2.7 to 3.7 error: “TypeError: 'generator' object is not subscriptable” “'生成器' object 不可下标”错误 - "'generator' object is not subscriptable" error TypeError: 'NoneType' object 不可订阅:JSON 文件 - TypeError: 'NoneType' object is not subscriptable: JSON file
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM