2017-01-14 3 views
-1

私は以下の指示で練習問題の正しい値を得るのが難しいです。 読み込み用にファイルを開き、バイト数と改行( '\ n')の数を返す関数を作成します。Pythonのテキストファイルのカウント行を修正し、サイズをバイト単位で取得するにはどうすればよいですか?

def readFile(tmp.txt)の値は(12, 4)ですが、私は(11, 5)です。

ここで私は間違っています、そして、あなたはそれがなぜ大変詳細に説明できるのでしょうか?

def readFile(filename): 
    f = open(filename, 'r') 
    size = 0 # Total size in bytes of all lines in a text file 
    lines = 0 # Total number of lines 
    buf = f.readline() # Read a line  
    while buf != "": 
     buf = f.readline() # Read a line 
     size += len(buf) 
     lines += 1 # Count lines 
    f.close # Close a file    

    return (size, lines) 
+0

あなたが言ったtmp.txtの内容を共有できますか? –

+2

なぜあなたはあなたが読んだ最初の 'buf'を投げ捨てていますか? – usr2564301

+0

また、これらのことを実行するために組み込み関数を使用することはできないと説明されていますか? os.path.getsize( 'tmp.txt')とopen( 'tmp.txt'、 'r')。read()。count( '\ n')はそれ以外の場合は完全にジョブを実行します。 –

答えて

0

os.path.getsize(filename)は、hereを参照してください。 file.read()を使用すると、.txtファイルの内容全体を読み込んで返します。hereを参照してください。次に、.count( "\ n")メソッドを使用して、\ nの出現回数を数えます。 .close()の段落を読んで、withキーワードを使うことをお勧めします(前のリンクを参照)。

注:次のコードスニペットは、tmp.txtが.pyファイルと同じフォルダにあることを前提としています。

import os 


def read_file(filename): 
    nr_of_bytes = os.path.getsize(filename) 
    with open(filename, "r") as file: 
     nr_of_newlines = file.read().count("\n") 
    return nr_of_bytes, nr_of_newlines 

print(read_file("tmp.txt")) 

短いバージョン:

import os 


def read_file(filename): 
    with open(filename, "r") as file: 
     nr_of_newlines = file.read().count("\n") 
    return os.path.getsize(filename), nr_of_newlines 

print(read_file("tmp.txt")) 
+0

私の答えを更新しました。 –

0

Finaly私は正しい結果を得ることができました。 PyschoolのWebサイトでコーディングするときに、上記の組み込み関数の一部が機能しないため、おそらくコードがあります。

def readFile(filename): 
    f = open(filename, 'r') 
    string1 = f.read() # Read file 
    size = len(string1) # Getting file size, assuming length of a string represent 
         # file size (python 2.x) 
    f.close    # We close file temporarily, once we read all bytes, 
         # we cannot read file again (based on my experience with Python, perhaps I am wrong) 

    d = open(filename, 'r')  # Again we open same file 
    lines = d.read().count("\n") # Counting '\n' 
    d.close      # We close file 

    return (size, lines)   # Return result 
+0

ありがとうございました。 – Pifko6

関連する問題