>>> for fname in Path("data").glob("?-words.txt"): ... print(f"{fname}: {Path(fname).read_text().strip()}") ... data/a-words.txt: acclimations airways antinarrative astrocyte data/b-words.txt: buggiest biros bushvelds begazed braunite data/z-words.txt: zonate zoophyte zumbooruk zoozoos
이제 파일의 단어를 분리하여 목록에 저장합니다.
파일에서 단어를 읽어 목록에 저장하기
>>> def wordfile_to_list(fname, initial_words=[]):
... with open(fname) as words:
... initial_words.extend(words.read().split())
... return initial_words
...
>>> wordfile_to_list("data/z-words.txt", ["zlotys", "zappier"])
['zlotys', 'zappier', 'zonate', 'zoophyte', 'zumbooruk', 'zoozoos']
지금까지는 나쁘지 않습니다. 몇 가지 초기 목록 요소로 시작하되 파일에서 더 많은 요소를 읽어서 목록에 추가하고 싶을 수도 있습니다. 간단하므로 다시 해 봅시다.