Asa*_*Kim -5 python file-io seek eof python-2.7
为什么这两个函数的 print len() 值不同?它们不一样吗?
此脚本打开的文件是一个包含三行文本的文本文件。我将它命名为 test.txt,里面是
Jack and Jill
gave up
they went home with no water
Run Code Online (Sandbox Code Playgroud)
代码:
def function2nd (filename):
target = open(theFile, 'r')
inData = target.read()
print inData
print len(inData)
target.close()
theFile = raw_input("What is the file name?\n>>")
function2nd(theFile)
def function3rd (filename):
target = open(theFile, 'r')
target.read()
print target.read()
print len(target.read())
target.close()
function3rd(theFile)
Run Code Online (Sandbox Code Playgroud)
文件就像磁带盒中的长磁带;您可以读取文件,但是当您完成时,您已经将磁带一直传递到最后。重读不会给你的数据再次。
因此,您的第二个函数试图从已经一直缠绕到最后的文件中读取数据。
您可以通过重新打开文件或使用target.seek(0)将其发送回开始来倒带“磁带” 。
| 归档时间: |
|
| 查看次数: |
475 次 |
| 最近记录: |