在Python 3.x中从文件读取令牌
有没有什么方法可以不管文件格式如何,按“标记”来读取文件中的信息呢?举个例子,如果我想从一个输入文件生成一个ppm格式的图片,而文件中的两个像素是
255 0 0
0 0 255
但它显示成了
255
0 0
0
0 255
在这种情况下,我想按“标记”来读取,而不是在我的循环中按行读取,但我找不到任何内置的方法来做到这一点。
2 个回答
1
你可以使用 chain.from_iterable
,这里的可迭代对象是 line.split() for line in fin
:
>>> with open('temp.txt', 'r') as fin:
... iter = chain.from_iterable(line.split() for line in fin)
... print(list(iter))
...
['255', '0', '0', '0', '0', '255']
3
你可以自己写一个文件迭代器:
class file_tokens:
def __init__(self, file):
self.file = file
self.line = []
def __iter__(self):
return self
def next(self):
while not len(self.line):
self.line = self.file.readline()
if not self.line:
raise StopIteration
self.line = self.line.split()
return self.line.pop(0)
然后就像使用普通文件一样使用它:
for token in file_tokens(open(infile)):
print('Token: ' + token)