简体   繁体   中英

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. The filestoExperiment text is not empty.

Whats wrong here ? Could someone point out

By doing, myfile.readlines() you already read the entire file. 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. 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).

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.

  1. readlines() - returns the complete file as a "list of strings each separated by \\n" for example,

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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