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.
输出看起来很奇怪,因为它也在打印新行。如果计算它打印的字符数,则在考虑换行符时输出是正确的。
当你调用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时,它会将光标位置移动指定的字符数。当你再次打电话给它时,它会从它停止的地方回来。如果不指定数字,它将一直读到文件末尾。