Dùng module os để duyệt thư mục, lọc file .txt, đọc nội dung từng file.
Ví dụ minh họa
import os
path = r"C:/Users/Sairam/Documents/"
os.chdir(path)
def read_files(file_path):
with open(file_path, 'r') as file:
print(file.read())
for file in os.listdir():
if file.endswith('.txt'):
file_path = f"{path}/{file}"
read_files(file_path)
Kết quả đầu ra
Sample 1 ======== Welcome to Tutorialspoint. You are browsing the best resource for Online Education. Sample 2 ======== A distributed ledger is a type of data structure...
Chương trình đọc và in nội dung 2 file .txt trong thư mục.