Program Python Membaca File Baris demi Baris Ke Daftar

0
(0)

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']

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.


Notice: ob_end_flush(): failed to send buffer of zlib output compression (0) in /home/breatgem/widiyanata.com/wp-includes/functions.php on line 4755