65 — Files: processing many files
Guide 13 read one file you named in the code. Real folders hold
many files, and you usually do not know their names ahead of time.
os.listdir(".") lists every name in a folder, and file_read from guide
13 reads whichever one you point at. Together they turn a whole
folder into a list you can loop over.
Steps
Create two small text files next to your program.
one.txt:
run it →the cat sat on the mat the dog ran past the catAnd
two.txt:
run it →a bird sang on the roofimport osloads Python's folder tools, andos.listdir(".")returns a list of every name in the current folder —.means "this folder". Count the list withlen:
run it →import os names = os.listdir(".") show f"{len(names)} names in this folder"With the program and the two text files, that prints
3 names in this folder. The list contains every name, includingfiles-folder.nme— not just the text files..endswith(".txt")keeps only the text files. Aforloop reads each kept name withfile_readand splits it into words, exactly as guide 36 did for one file:
run it →import os use file latest for name in os.listdir("."): if name.endswith(".txt"): words = file_read(name).split() show f"{name}: {len(words)} words"two.txt: 6 words one.txt: 12 wordsLetters count the same way per file: remove the spaces and the line breaks, then take
len:
run it →use file latest text = file_read("one.txt") letters = len(text.replace(" ", "").replace("\n", "")) show lettersone.txthas 36 letters.The full program collects the
.txtnames first, reports each file, and then the totals and the biggest file across all of them. Savefiles-folder.nme:
run it →# files-folder.nme — words and letters across every .txt file. # Run: nme r files-folder # Create one.txt and two.txt in the same folder first. import os use file latest files = os.listdir(".") txt_files = [] for name in files: if name.endswith(".txt"): txt_files.append(name) show f"{len(txt_files)} txt files found:" total_words = 0 total_letters = 0 biggest = "" biggest_words = 0 for name in txt_files: text = file_read(name) words = text.split() letters = len(text.replace(" ", "").replace("\n", "")) total_words = total_words + len(words) total_letters = total_letters + letters if len(words) > biggest_words: biggest_words = len(words) biggest = name show f" {name}: {len(words)} words, {letters} letters" show "all files:" show f" words: {total_words}" show f" letters: {total_letters}" show f" biggest: {biggest} with {biggest_words} words"The
if len(words) > biggest_words:check remembers the file with the most words, the same "best so far" idea as the high score in guide 15.Run it with the two text files in the folder:
nme r files-folder2 txt files found: two.txt: 6 words, 18 letters one.txt: 12 words, 36 letters all files: words: 18 letters: 54 biggest: one.txt with 12 wordsThe program never names a file in advance:
os.listdirfound them, theifkept the.txtones, and the totals add the per-file counts.Korean writes the same steps with
import os,파일 사용 최신, and파일읽기; the full Korean program is in the Korean guide.
Try it yourself
Add a third file three.txt and rerun — it appears in the report with no
code change. Or change the filter to if name.endswith(".csv"): and count
lines instead of words: text.splitlines().
What you learned
os.listdir(".")returns every name in the current folder as a list..endswith(".txt")filters the list to the files you want.file_read(name)reads the file named by any string, not just a literal.- A
forloop over a folder turns one-file handling into many-file handling.