2016-10-20 55 views
2

所以我正在研究「學習python的難題」練習20,本課介紹了「seek()」函數來引用文件。在這種情況下,我們有:Python:尋求(0)和開放()基本上做同樣的事情?

def rewind(f): 
    f.seek(0) 

創建一個函數來調用尋求(0),這意味着做一個參考點,在程序中使用的文件的開頭。現在,在幾節課中,我們已經分配了一個變量用於打開文件,在這種情況下,爲current_file = open(input_file)

我的問題是,是否使用seek從(0)開始打開文件與再次使用打開命令是一樣的,如open(current_file)。有什麼區別?這裏是整個課程代碼:

from sys import argv 

script, input_file = argv 

def print_all(f): 
    print f.read() 

def rewind(f): 
    f.seek(0) 

def print_a_line(line_count, f): 
    print line_count, f.readline() 

current_file = open(input_file) 

print "First let's print the whole file:\n" 

print_all(current_file) 

print "Now let's rewind, kind of like a tape." 

rewind(current_file) 

print "Let's print three lines:" 

current_line = 1 
print_a_line(current_line, current_file) 

current_line = current_line + 1 
print_a_line(current_line, current_file) 

current_line = current_line + 1 
print_a_line(current_line, current_file) 
+0

Seek不打開文件,它倒帶當前文件。我確信這就是你的意思,但是_「使用seek從(0)開始打開文件」_是不同的。你能澄清嗎? – tdelaney

+1

btw'open(...,「a」)'打開文件並將指針移動到文件的末尾,以便它查找'seek(0,2)' – furas

+0

FYI:http://sopython.com/wiki/LPTHW_Complaints – jonrsharpe

回答

2

沒有,因爲你的示例代碼所示,seek作品的打開的文件對象open作品在文件名上。所不同的是有點微妙的,一個簡單的例子可能會更清楚:

f = open('myfile.txt') 
f.seek(5) 

你總是可以重新打開該文件,而不是尋求到零,但是這將是額外的開銷。

+0

除了額外的開銷之外,對於沒有名稱的打開文件(可能是因爲文件在打開後立即被刪除,如在'tempfile.TemporaryFile'的一些實現中),您不能重新打開它,但是您可以回到開始。同樣,對於像'gzip.open'這樣的其他像文件一樣的對象,只需在'fileobj.name'上調用普通的'open'就不會得到與向後查找等效的行爲,因爲您會遇到錯誤的處理程序。 – ShadowRanger

相關問題