Contoh program : Program Python untuk Mendapatkan Hitungan Baris dari File

0
(0)

Contoh 1: Menggunakan perulangan for

Isi filenya my_file.txt aku s

honda 1948
mercedes 1926
ford 1903

Kode sumber

def file_len(fname):
    with open(fname) as f:
        for i, l in enumerate(f):
            pass
    return i + 1

print(file_len("my_file.txt"))

Keluaran

3

Contoh 2: Menggunakan pemahaman daftar

num_of_lines = sum(1 for l in open('my_file.txt'))

print(num_of_lines)

Keluaran

3

How useful was this post?

Click on a star to rate it!

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate this post.