您现在的位置:首页 > 教案格式 > 正文

浮点数 非宁静,无以致远(2)

2018-01-03 09:01 网络整理 教案网

2. fileList = fileHandle.readlines()

3. for fileLine in fileList:

4. print '>>', fileLine

5. fileHandle.close()

fileHandle = open ( 'test.txt' )

fileList = fileHandle.readlines()

for fileLine in fileList:

print '>>', fileLine

fileHandle.close()

或者在文件中一次读取几个字节的内容:

1. fileHandle = open ( 'test.txt' )

2. print fileHandle.read ( 1 ) # "T"

3. fileHandle.seek ( 4 )

fileHandle = open ( 'test.txt' )

print fileHandle.read ( 1 ) # "T"

fileHandle.seek ( 4 )

随机访问文件中的位置 seek

Python在读取一个文件时,会记住其在文件中的位置,如下所示:

1. fileHandle = open ( 'test.txt' )

2. garbage = fileHandle.readline()

3. fileHandle.readline() # "Really, it is."fileHandle.close()

fileHandle = open ( 'test.txt' )

garbage = fileHandle.readline()

fileHandle.readline() # "Really, it is."fileHandle.close()

可以看到,只有第二行显示出来。然而,我们可以让Python从头开始读来解决这个问题:

1. fileHandle = open ( 'test.txt' )

2. garbage = fileHandle.readline()

3. fileHandle.seek ( 0 )

4. print fileHandle.readline() # "This is a test."

5. fileHandle.close()

fileHandle = open ( 'test.txt' )

garbage = fileHandle.readline()

fileHandle.seek ( 0 )

print fileHandle.readline() # "This is a test."

fileHandle.close()

在上面这个例子中,我们让Python从文件第一个字节开始读取数据。所以,第一行文字显示了出来。当然,我们也可以获取Python在文件中的位置:

1. fileHandle = open ( 'test.txt' )

2. print fileHandle.readline() # "This is a test."

3. print fileHandle.tell() # "17"

4. print fileHandle.readline() # "Really, it is."

fileHandle = open ( 'test.txt' )

print fileHandle.readline() # "This is a test."

print fileHandle.tell() # "17"

print fileHandle.readline() # "Really, it is."