将文件列表连接到Python中的字符串列表中

时间:2013-04-21 00:23:10

标签: python file concatenation

我正在尝试创建一个类对象,其构造函数接收文件列表,将每个对象转换为字符串列表(每行一个)并将所有列表连接在一起并存储它。该类还包含一个成员函数,该函数从列表中输出随机行

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()会从连接文件字符串列表中生成一个字符串,不是吗?所以我很难搞清楚问题所在。

1 个答案:

答案 0 :(得分:1)

应该是

self.lines += f.readlines() # notice the += 
# self.lines.extend(f.readlines()) is equivalent

但是,您可以使用fileinput代替

import fileinput
lines = list(fileinput.input(paths))