简体   繁体   English

Python输入/输出说明

[英]Python input/Output explanation

      my_file = open("text.txt", "r")
      print my_file.readline()
      print my_file.readline()
      print my_file.readline()
      my_file.close()

I understand that/how this prints out the first three lines of the text file, but I'm not entirely sure why . 我知道这/如何打印出文本文件的前三行,但我不确定为什么 Since I'm printing out my_file.readline(), why doesn't it print out the first line for all three times? 由于我要打印出my_file.readline(),为什么它不打印出所有三行的第一行?

Python reads in the file and stores it in the variable my_file with the pointer at the start of the file or (0, 0) . Python读取文件并将其存储在变量my_file ,并且指针位于文件开头或(0, 0) As you start doing readline , python will read a line from the file and then "consume" it. 当您开始执行readline ,python将从文件中读取一行,然后“使用”它。 In other words, the current pointer will now be waiting at the next line so when you call readline , it will now get the next line. 换句话说,当前指针现在将在下一行等待,因此当您调用readline ,它将现在获得下一行。

Hope that helps 希望能有所帮助

The equivalent of what you are expecting would be: 与您期望的等效:

my_file = open("text.txt", "r")
print my_file.readline()
my_file.seek(0, 0)
print my_file.readline()
my_file.seek(0, 0)
print my_file.readline()
my_file.close()

In the above case, the seek(0, 0) call resets the pointer's position to the start of the file after every readline so in this case, you will end up printing the first line 3 times. 在上述情况下,在每次readline之后, seek(0, 0)调用会将指针的位置重置为文件的开头,因此在这种情况下,您将结束打印第一行3次。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM