Program Python Membaca File Baris demi Baris Ke Daftar

Contoh 1: Menggunakan readlines ()

Isi dari file data_file.txt adalah

honda 1948
mercedes 1926
ford 1903

Kode sumber

with open("data_file.txt") as f:
    content_list = f.readlines()

# print the list
print(content_list)

# remove new line characters
content_list = [x.strip() for x in content_list]
print(content_list)

Keluaran

['honda 1948n', 'mercedes 1926n', 'ford 1903']
['honda 1948', 'mercedes 1926', 'ford 1903']

readlines() mengembalikan daftar baris dari file.


Contoh 2: Menggunakan pemahaman loop dan daftar

with open('data_file.txt') as f:
    content_list = [line for line in f]

print(content_list)

# removing the characters
with open('data_file.txt') as f:
    content_list = [line.rstrip() for line in f]

print(content_list)

Keluaran

['honda 1948n', 'mercedes 1926n', 'ford 1903']
['honda 1948', 'mercedes 1926', 'ford 1903']