[英]How to read from a file using only readline()
The code i have right now is this 我现在拥有的代码是这样
f = open(SINGLE_FILENAME)
lines = [i for i in f.readlines()]
but my proffessor demands that 但是我的校长要求
You may use readline(). 您可以使用readline()。 You may not use read(), readlines() or iterate over the open file using for.
您不得使用read(),readlines()或使用for来迭代打开的文件。
any suggestions? 有什么建议么? thanks
谢谢
You could use a two-argument iter()
version : 您可以使用两个参数的
iter()
版本 :
lines = iter(f.readline, "")
If you need a list of lines: 如果需要行列表:
lines = list(lines)
First draft: 第一稿:
lines = []
with open(SINGLE_FILENAME) as f:
while True:
line = f.readline()
if line:
lines.append(line)
else:
break
I feel fairly certain there is a better way to do it, but that does avoid iterating with for, using read, or using readlines. 我确信可以确定有更好的方法,但这确实避免了for,使用read或使用readlines进行迭代。
You could write a generator function to keep calling readline()
until the file was empty, but that doesn't really seem like a large improvement here. 您可以编写一个生成器函数来继续调用
readline()
直到该文件为空为止,但这似乎并没有太大的改进。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.