您可以在Python中模仿C语言。要读取不超过max_size字节数的缓冲区,可以执行以下操作:with open(filename, 'rb') as f: while True: buf = f.read(max_size) if not buf: break process(buf)或者,一行一行地显示文本文件:# warning -- not idiomatic Python! See below...with open(filename, 'rb') as f: while True: line = f.readline() if not line: break process(line)您需要使用while True / break构造函数,因为除了缺少读取返回的字节以外,Python中没有eof测试。在C语言中,您可能具有:while ((ch != '\n') && (ch != EOF)) { // read the next ch and add to a buffer // ..}但是,您不能在Python中使用此功能: while (line=f.readline()): # syntax error因为Python的表达式中不允许赋值。在Python中这样做当然更惯用了:# THIS IS IDIOMATIC Python. Do this:with open('somefile') as f: for line in f: process(line)
用于打开文件并逐行读取的Python习惯用法是:with open('filename') as f: for line in f: do_something(line)该文件将在上述代码的末尾自动关闭(该with结构将完成此工作)。最后,值得注意的是line将保留尾随的换行符。可以使用以下方法轻松删除它:line = line.rstrip()