简体   繁体   English

使用和不使用 readlines() 方法打印文件的内容

[英]Printing contents of a file with and without using readlines() method

I have started learning python and came across the following code to print the contents of a file:我已经开始学习 python 并遇到以下代码来打印文件的内容:

with open('Example2.txt','r') as readfile:
     for line in readfile:
          print(line)

The output was as follows: output如下:

This is line A

This is line B

This is line C

This is line D

The source if the information says that the for loop takes input line by line and then prints it, but as far as I know (please correct me if I am wrong), the variable readfile contains a single string then how come the loop is running multiple times?如果信息说for循环逐行输入然后打印它的来源,但据我所知(如果我错了请纠正我),变量readfile包含一个字符串那么循环是如何运行的多次? It must be printing the contents of the file in a single go.它必须在单个 go 中打印文件的内容。

Also, this is the code that I think is correct to read the file line by line and this prints the same output too.另外,这是我认为可以逐行读取文件的正确代码,它也会打印相同的 output。 Then what is the difference between the previous code and this code?那么之前的代码和这段代码有什么区别呢?

with open('Example2.txt','r') as readfile:
     for line in readfile.readlines():
          print(line)

Actually, the readfile variable is a file object, which has an __iter__ method, where each index of the __iter__ corresponds to a line in your file.实际上, readfile变量是一个文件 object,它有一个__iter__方法,其中__iter__的每个索引对应于文件中的一行。 For more information, check this similar question: Reading files in Python with for loop有关更多信息,请查看类似的问题: Reading files in Python with for loop

The actual type definition can be found here and it inherits from BufferedIOBase , which in turn inherits from IOBase , where the readlines method is defined实际的类型定义可以在这里找到,它继承自BufferedIOBase ,后者又继承自IOBase ,其中定义了readlines方法

The difference between the two code snippets is that in the first one, you're relying on the implementation of TextIOWrapper , which is essentially syntactic sugar, to call readlines for you, while in the second one, you're explicitly making the call.两个代码片段之间的区别在于,在第一个代码片段中,您依赖TextIOWrapper的实现(本质上是语法糖)来为您调用readlines ,而在第二个代码片段中,您正在显式进行调用。

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

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