2014-06-11 17 views
1

我目前正在通過免費的在線python學校工作。下面的模板已經給了我,我將完成該函數,以便它返回文件的大小(字節數)和換行符的數量(「\ n」)。我完全被卡住了。任何幫助,將不勝感激。打開文件進行讀取並返回字節數和換行符的函數

def readFile(filename): 
    f = open(filename) 
    size = 0 
    lines = 0 
    buf = f.read()  
    while buf!="": 



     buf = f.read() 

    f.close()     

    return (size, lines) 
+0

呃。 Python'學校'不使用'with'。 xD – BeetDemGuise

+0

這可能是一個非常早期的練習,他們不想混淆這個問題。 –

回答

2

所以buf變量包含一塊數據。

既然你還在學習,我會用一種很基本的方法:

nl_count = 0 # Number of new line characters 
tot_count = 0 # Total number of characters 
for character in buf: 
    if character == '\n': 
     nl_count += 1 
    tot_count += 1 

現在,你將不得不調整這適合你的代碼,但是這應該給你的東西開始。

+0

謝謝,這有很大的幫助。我也可以問,while循環中包含的「buf = f.read()」的意義是什麼?謝謝 – user3636636

+0

閱讀在'EOF'處結束。你可以通過設置緩衝區大小:'buf = f.read(buffer_size)'。我正在糾正,但這裏可能有一個默認值,您可能在非常大的文件中達到'EOF'之前觸發該默認值。 (所以你會想要讀取循環內的其餘部分) – cchristelis

0

您可以一次讀取所有行,並使用列表而不是文件本身。例如,

def readFile(filename="test.txt"): 

    f = open(filename) 

    # Read all lines in at once 
    buf = f.readlines() 
    f.close() 

    # Each element of the list will be a new line 
    lines = len(buf) 

    # The total of the total of each line 
    size = sum([len(i) for i in buf]) 

    return (size, lines) 
+1

但是,這種方法會失敗,並且會出現非常大的文件。此外,學校給了一個模板來使用,而這並沒有使用它。 –

相關問題