16 — Name list: read lines from a file
A file can be a list. When each name sits on its own line, one Python method,
splitlines(), turns the whole file into a list of names.
Steps
Create
names.txtwith one name per line, next to your program:
run it →Mina Sana 준호 YunaRead the whole file and split it into lines:
run it →use file latest names = file_read("names.txt").splitlines() show namesRun
nme r names. The console shows['Mina', 'Sana', '준호', 'Yuna'].file_readreturns the text and.splitlines()cuts it at every line break. This line is ordinary Python, so it stays exactly as written.Loop over the list with a
forblock. Sentence NME works inside it:
run it →use file latest names = file_read("names.txt").splitlines() for name in names: show Hello nameThis prints one
Helloper name.Pick a random name with
random_pick.use random latestloads the picker;3 times:repeats the pick:
run it →use file latest use random latest names = file_read("names.txt").splitlines() 3 times: show random_pick(names)Korean reads with
파일읽기(...).splitlines()and picks with랜덤선택:
run it →파일 사용 최신 랜덤 사용 최신 이름들 = 파일읽기("names.txt").splitlines() 3번: 이름 = 랜덤선택(이름들) 안녕하세요 이름! 말해줘
Try it yourself
Add two names to names.txt, rerun, and watch the list and picks grow.
What you learned
file_read(path).splitlines()/파일읽기(경로).splitlines()reads every line of a file into a list.- A
for name in names:block visits each entry; sentence NME works inside it. random_pick(names)/랜덤선택(이름들)chooses one entry at random.3 times:/3번:repeats the pick so a game can ask again.