我正在尝试创建一个类对象,其构造函数接收文件列表,将每个文件转换为字符串列表(每行一个)并将所有列表连接在一起并存储它。此类还包含一个成员函数,它从列表中输出随机行
class randline:
def __init__(self, filename = [] ):
#def __init__(self, filename = [] , *args):
#for i in range(len(filename)):
self.lines = []
for path in filename:
with open(path, 'r') as f:
self.lines + f.readlines()
f.close()
def chooseline(self):
if self.lines:
return random.choice(self.lines)
def main():
#...
try:
generator = randline(args)
for index in range(numlines):
sys.stdout.write(generator.chooseline())
except IOError as (errno, strerror):
parser.error("I/O error({0}): {1}".
format(errno, strerror))
这会产生错误消息:
Traceback (most recent call last):
File "./1randline.py", line 59, in <module>
main()
File "./1randline.py", line 53, in main
sys.stdout.write(generator.chooseline())
TypeError: expected a character buffer object
但是chooseline() 从连接的文件字符串列表中生成一个字符串,不是吗?所以我很难弄清楚问题是什么。