TypeError:“list”不支持缓冲区接口。

时间:2022-12-10 18:22:40

I have a program that asks the user 10 questions then saves it to the file. All of that works perfectly however I am then trying to read a set of files that have been saved, which raises the aforementioned TypeError.

我有一个程序,问用户10个问题,然后保存到文件中。所有这些都可以很好地工作,但是我正在尝试读取一组已保存的文件,这将导致前面提到的TypeError。

The code that is causing the problem is this:

导致问题的代码是:

def readfile():
    classtoload = input("Which class would you like to load: ")
    gclass = "Class_" + classtoload
    script_dir = os.path.dirname(os.path.abspath(__file__))
    globclass = os.path.join(script_dir, gclass)
    list_of_files = glob.glob(globclass + '\*.pkl')
    files = []
    files.append(list_of_files)
    print(files)
    for s in files:
        load = os.path.dirname(os.path.abspath(s))
        pickle.load(load)

The full error is this:

完全错误是这样的:

Traceback (most recent call last):
  File "C:\Users\Liam\Documents\LIWA HW\Python programs\maths question.py", line 102, in <module>
    ts()
  File "C:\Users\Liam\Documents\LIWA HW\Python programs\maths question.py", line 10, in ts
    readfile()
  File "C:\Users\Liam\Documents\LIWA HW\Python programs\maths question.py", line 96, in readfile
    load = os.path.dirname(os.path.abspath(s))
  File "C:\Users\Liam\Documents\LIWA HW\python\lib\ntpath.py", line 547, in abspath
    path = _getfullpathname(path)
TypeError: 'list' does not support the buffer interface

My full code is this:

我的全部代码是:

import random, re, pickle, os, glob

def ts():
    tors = ""
    while tors not in ["T","S"]:
        tors = input("are you a teacher or student: ").upper()
    if tors == "S":
        name_enter()
    else:
        readfile()

def name_enter():
    global forename, surname
    forename, surname = "", ""
    while forename == "" or len(forename) > 25 or not re.match(r'^[A-Za-z0-9-]*$', forename):
        forename = input("Please enter your forename: ")
    while surname == "" or len(surname) > 30 or not re.match(r'^[A-Za-z0-9-]*$', surname):
        surname = input("Please enter your surname: ") 
    enter_class()


def enter_class():  
    global class_choice     
    class_choice = None     
    while class_choice not in ["1","3","2"]:    
        class_choice = input("Please enter you class (1, 2, 3): ") 
    print("\nClass entered was " + class_choice)
    mathsquestion()

def mathsquestion():
    global qa, score
    qa, score = 0, 0
    for qa in range(0,10):
        qa = qa + 1
        print("The question you are currently on is: ", qa)
        n1, n2, userans = random.randrange(12), random.randrange(12), ""
        opu = random.choice(["-","+","x"])
        if opu == "+":
            while userans == "" or not re.match(r'^[0-9,-]*$', userans):
                userans = input("Please solve this: %d" % (n1) + " + %d" % (n2) + " = ") 
            prod = n1 + n2
        elif opu == "-":
            while userans == "" or not re.match(r'^[0-9,-]*$', userans):
                userans = input("Please solve this: %d" % (n1) + " - %d" % (n2) + " = ") 
            prod = n1 - n2
        else:
            while userans == "" or not re.match(r'^[0-9,-]*$', userans):
                userans = input("Please solve this: %d" % (n1) + " x %d" % (n2) + " = ") 
            prod = n1 * n2
        userans = int(userans)
        prod = int(prod)
        if prod == userans:
            score = score + 1
            print("Well done, you have got the question correct. Your score is now: %d" % (score))
        else:
            print("Unfortunatly that is incorrect. The answer you entered was %d" % (userans) + " and the answer is actually %d" % (prod))

    print("Your final score is: %d" % (score))
    savefile()

def savefile():
    file = forename + "_" + surname + ".pkl"
    script_dir = os.path.dirname(os.path.abspath(__file__))
    dest_dir = os.path.join(script_dir,'Class_' + class_choice)
    scoresave = {"%d" % score}
    try:
        os.makedirs(dest_dir)
    except OSError:
        pass 
    path = os.path.join(dest_dir, file)
    with open(path, 'ab') as stream:
        pickle.dump(scoresave, stream)
    lists = []
    infile = open(path, 'rb')
    while True:
        try:
            lists.append(pickle.load(infile))
        except EOFError:
            break
    obj=lists[0]
    while len(lists) > 3:
        lists.pop(0)
    print(lists)
    infile.close()

def readfile():
    classtoload = input("Which class would you like to load: ")
    gclass = "Class_" + classtoload
    script_dir = os.path.dirname(os.path.abspath(__file__))
    globclass = os.path.join(script_dir, gclass)
    list_of_files = glob.glob(globclass + '\*.pkl')
    files = []
    files.append(list_of_files)
    print(files)
    for s in files:
        load = os.path.dirname(os.path.abspath(s))
        pickle.load(load)

1 个解决方案

#1


1  

files is a list of lists, because you append the list of names to it:

文件是列表的列表,因为您将名称列表附加到它:

list_of_files = glob.glob(globclass + '\*.pkl')
files = []
files.append(list_of_files)

You now have a list containing one element, another list. So when iterating over files, you get that one list again:

现在有一个包含一个元素的列表,另一个列表。所以当遍历文件时,你会再次得到一个列表:

for s in files:
    load = os.path.dirname(os.path.abspath(s))

which fails because s should be a string.

因为s应该是字符串。

Use list.extend() instead:

使用list.extend():

files.extend(list_of_files)

or better still, just use list_of_files directly:

或者更好的是,直接使用list_of_files:

for s in list_of_files:

#1


1  

files is a list of lists, because you append the list of names to it:

文件是列表的列表,因为您将名称列表附加到它:

list_of_files = glob.glob(globclass + '\*.pkl')
files = []
files.append(list_of_files)

You now have a list containing one element, another list. So when iterating over files, you get that one list again:

现在有一个包含一个元素的列表,另一个列表。所以当遍历文件时,你会再次得到一个列表:

for s in files:
    load = os.path.dirname(os.path.abspath(s))

which fails because s should be a string.

因为s应该是字符串。

Use list.extend() instead:

使用list.extend():

files.extend(list_of_files)

or better still, just use list_of_files directly:

或者更好的是,直接使用list_of_files:

for s in list_of_files: