从python 3.x中的文件读取令牌 [英] Reading tokens from a file in python 3.x
本文介绍了从python 3.x中的文件读取令牌的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否有某种方式可以通过令牌从文件中读取信息,而与格式无关?例如,如果我尝试从输入文件中生成ppm图像,而不是2个像素
Is there some way to read in information from a file by token regardless of the formatting? For example, if I am trying to generate a ppm image from an input file and instead of 2 pixels being
255 0 0
0 0 255
它显示为
255
0 0
0
0 255
在这种情况下,我想通过令牌读取而不是在循环中按行读取,但是我找不到与此相关的任何内置方法.
I'd like to read by token in this situation instead of by line in my loop but I can't find any built in methods regarding this.
推荐答案
您始终可以滚动自己的文件迭代器:
You could always roll your own file iterator:
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)
然后像普通文件一样使用:
Then use like a normal file:
for token in file_tokens(open(infile)):
print('Token: ' + token)
这篇关于从python 3.x中的文件读取令牌的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文