简体   繁体   English

文件open(),readLines()

[英]file open() , readLines()

 import os.path
 os.path.exists('~/fileToExperiment.txt')
 myfile = open('~/fileToExperiment.txt','r')
 myfile.readlines()

 for line in myfile:
     print line

So I am trying to run this very simple python code but it doesnot output anything nor does it has any errors. 所以我试图运行这个非常简单的python代码,但是它不输出任何东西,也没有任何错误。 The filestoExperiment text is not empty. filestoExperiment文本不为空。

Whats wrong here ? 这是怎么了 Could someone point out 有人可以指出

By doing, myfile.readlines() you already read the entire file. 这样, myfile.readlines()就已经读取了整个文件。 Then, we you try to iterate over your file object, you already are at the end of the file. 然后,我们尝试遍历文件对象,您已经在文件末尾了。

A better practice is to do: 更好的做法是:

with open('~/fileToExperiment.txt','r') as myfile:
    for line in myfile:
        print line

myfile.readlines() will store the whole content of the file in memory. myfile.readlines()将文件的全部内容存储在内存中。 If you do not need the entire content at once, it is best to read line by line. 如果您一次不需要全部内容,则最好逐行阅读。

If you do need the entire content, you can use 如果确实需要全部内容,则可以使用

with open('~/fileToExperiment.txt','r') as myfile:
    content = myfile.read() ## or content = myfile.readlines()

Also note the use of the with statement, which is recommended when handling files (no need to close the file afterwards). 还要注意使用with语句,该语句在处理文件时建议使用(以后无需关闭文件)。

You didn't store the lines in a variable. 您没有将行存储在变量中。 So try this: 所以试试这个:

 lines = myfile.readlines()

 for line in lines:
     print line

You can use either readlines() or looping file object to print or read the lines from file. 您可以使用readlines()循环文件对象来打印或读取文件中的行。

  1. readlines() - returns the complete file as a "list of strings each separated by \\n" for example, readlines()-例如,以“每个用\\ n分隔的字符串列表”形式返回完整文件,

code: 码:

    print myfile.readlines()

output: 输出:

    ['Hello World\n', 'Welcome to Python\n', 'End of line\n']
  1. Looping file object - You can loop over the file object for reading lines from a file. 循环文件对象-您可以在文件对象上循环以读取文件中的行。 This is memory efficient, fast, and leads to simple code . 这是高效,快速的内存,并导致简单的代码 For example, 例如,

code: 码:

    myfile = open('newfile.txt', 'r')

    for line in myfile:
      print line

output: 输出:

    Hello World
    Welcome to Python
    End of line

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

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