I have some different format files in a one directory, but i want to read only .txt file and print the based on the count ,
Example: (one.txt,two.txt,three.txt,four.txt,one.xlsx,two.xlsx)
here i want to count the .txt files and read all .txt file one by one , here the count is 4
read file one.txt
print(“hello”)
read file two.txt
print(“hello”)
read file three.txt
print(“hello”)
read file four.txt
print(“hello”)
Advertisement
Answer
You can use pathlib package from the standard library:
from pathlib import Path myfolder = Path("PATH_TO_YOUR_FOLDER") txt_files = [p for p in myfolder.iterdir() if p.suffix == ".txt"] print("Total number of txt files:", len(txt_files)