Reading a Text File

  1. open
f = open('4sbwinners.txt','r')
  1. You can then use the readline method to read each line from the file. Note that when the end of the file is reached, readline returns an empty string (''):
f.readline()


In [2]: f.readline()
Out[2]: 'Packers\n'

In [3]: f.readline()
Out[3]: 'Packers\n'

In [4]: f.readline()
Out[4]: 'Jets\n'

In [5]: f.readline()
Out[5]: 'Chiefs'

In [6]: f.readline()
Out[6]: ''

read line by line

for line in f:
    print line

read line by line and strip whitespace

for line in f:
    print line.strip()
  1. close
f.close()

The with Statement

f is open for all of the indented statements below the with statements. Once you outdent to the global level, f is automatically closed. Using the with statement like this for files is considered best practice.

with open('4sbwinners.txt','r') as f:
    for line in f:
        print line.strip()

Instead of reading a file sequentially, we can easily turn a file into an in-memory list using the list() function:

with open('4sbwinners.txt','r') as f:
    winners = list(f)


三种read file 方法

There are at least 3 ways to read a text file (known as f) into memory as a list object:

  1. Using the list(f) function, as demonstrated in the lesson.
  2. f.readlines() will read all lines in the file and return a list
  3. You can manually read the file, line by line, and build a list using a for loop
def list1(input):
    with open(input,'r') as f:
        result = list(f)
    return result

def list2(input):
    with open(input,'r') as f:      
            result= f.readlines()           
    return result

def list3(input):
    result = []
    with open(input,'r') as f:
        for line in f:
            result.append(line)
    return result

results matching ""

    No results matching ""