打开文件错误:TypeError:强制转换为Unicode:需要字符串或缓冲区,找到列表

时间:2013-06-18 19:11:48

标签: python

我有以下代码:基本上我正在做的是,正在寻找一个.csv文件,它可能在两个地方之一(或更多) 我在文本文件(LocationsFile.txt).

中有两个特定位置

除此之外,我只想获得学生的特定字段:这是SSID Field

我有以下代码,但它似乎给我的错误如下:

    Tape Name130322
['\\\\....HIDDEN FOR Confidenciality .....StudentDB1_av.csv']
Success:
Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Python27\lib\lib-tk\Tkinter.py", line 1410, in __call__
    return self.func(*args)
  File "C:\Users\Administrator\Desktop\John\Spreadsheet\Gui.py", line 291, in run
    findStudentData('130322','StudentDB1')
  File "C:\Users\Administrator\Desktop\John\Spreadsheet\Gui.py", line 62, in findStudentData
    with open(items) as f:
TypeError: coercing to Unicode: need string or buffer, list found

正在执行的代码如下: - 在回复时请务必考虑,因为我是新手' python程序员!

def findStudentData(student_name,course):
student_name= student_name.lower()
configfiles = []

print "student_name" + student_name
for path in MMinfo_paths:
    configfiles.append(glob.glob(path+"/" + course+"*"))

for items in configfiles:
    print items
    print "Success:"
    heading = True

    with open(items) as f:
        content = f.read()

        if heading == True
            ssidCol = content.index('ssid')
            flagsCol = content.index('flags')
            nameCol = content.index('name')
            heading = False
            continue



        for item in rowData:
            if rowData.index(item) == nameCol:
                print rowData
            else:
                continue

非常感谢: - )

2 个答案:

答案 0 :(得分:2)

现在,您的配置文件如下所示:

[[file1, file2], [file3, file4]]

你可以这样做:

for items in configfiles:
    for filename in items:
        with open(items) as f: ...

或者,您可以使用configfiles.extend替换configfiles.append。 Append将glob返回的列表添加为configfiles列表的元素,而extend将glob返回的列表的每个元素添加到configfiles列表中。然后,configfiles将是:

[file1, file2, file3, file4]

你可以写:

for items in configfiles:
    with open(items) as f: ...

答案 1 :(得分:1)

items是代码中的列表,它应该是一个字符串。

glob.glob函数返回一个列表,因此您的configfiles变量是一个列表列表。

for items in configfiles:
    print items        # items is a list here
    print "Success:"
    heading = True

    with open(items) as f:  # list instead of string here, is incorrect.