python read()函数读取的字符多于指定的字符

时间:2019-02-24 05:25:12

标签: python readfile

first_file.txt

“
Hello World
This is our new text file
and this is another line.
Why? Because we can.
“

结果与我联系,请参见下文。

with open('first_file.txt') as f:
    print(f.read(2))
    print(f.read(3))
    print(f.read(8))
    print(f.read(15))
    print(f.read()) 

有人可以解释read(8)和read(15)吗?输出见下文。

He
llo
 World
T
his is our new 
text file
and this is another line.
Why? Because we can.

1 个答案:

答案 0 :(得分:3)

输出看起来很奇怪,因为它也在打印新行。如果计算要打印的字符数,则考虑换行符时输出正确。

调用print()时,python将在输出中添加换行符。以下是每次调用print时python看到的内容:

>>> f.read(2):  'He'+\n              <- 2 characters + newline
>>> f.read(3):  'llo'+\n             <- 3 characters + newline
>>> f.read(8):  ' World\nT'+\n       <- 8 characters + newline
>>> f.read(15): 'his is our new '+\n <- 15 characters + newline
>>> 
>>> f.read():   'text file\nand this is another line.\nWhy? Because we can.'+\n

当您调用文件上的read时,它将光标位置移动指定的字符数。再次调用read时,它将从上次中断的地方重新开始。如果您不指定数字,它将一直读取到文件末尾。