简体   繁体   English

如何仅使用readline()从文件读取

[英]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.

相关问题 在函数中使用readline()来读取日志文件不会进行迭代 - using readline() in a function to read through a log file will not iterate 忽略使用file.readline(size)之后读取的其余行 - Ignore the rest of the line read after using file.readline(size) 如何使用python从文件中仅读取数字以列为整数 - How to read numbers only to list as integer, from a file using python Python:从文件读取空格分隔的字符串,类似于readline - Python: Read whitespace separated strings from file similar to readline Python 文件 read() 和 readline() 计数器? - Python file read() and readline() counter? 使用 readline 限制读取的数量 - Limiting amount read using readline 如何将 python serial.readline() 数据中的数据读入字符串 - how to read data from python serial.readline() data into string 使用 readline() 从文件中将文本显示到 pygame window - Displaying text onto pygame window from file using readline() 在python中使用readline()读取txt文件,但在aws comprehend api中未读取第二行 - using readline() in python to read a txt file but the second line is not read in aws comprehend api 从长寿命的FIFO读取时,为什么只有readline()而不是read()或readlines()返回? - Why does only readline(), and not read() or readlines(), return when reading from a long-lived FIFO?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM