Python จัดการไฟล์ อ็อบเจกต์ และสร้างแอปพลิเคชันต่างๆ ได้ เราสามารถใช้ส่วนขยายและแพ็กเกจของ Python สร้างและพัฒนาแอปพลิเคชันเต็มรูปแบบ
สมมติว่าคุณต้องการควบคุมไฟล์ในระบบ Python มีโมดูล OS ซึ่งมีฟังก์ชันระบบเพื่อโต้ตอบกับไฟล์ในระบบปฏิบัติการ
มาดูวิธีอ่านไฟล์ข้อความหลายไฟล์จากโฟลเดอร์ด้วยโมดูล OS ใน Python:
- นำเข้าโมดูล OS ในสมุดบันทึก
- กำหนดพาธที่ไฟล์ข้อความตั้งอยู่ในระบบ
- สร้างลิสต์ไฟล์และวนลูปตรวจสอบว่าไฟล์ทุกไฟล์มีส่วนขยายถูกต้องหรือไม่
- อ่านไฟล์ด้วยฟังก์ชันที่กำหนดในโมดูล
ตัวอย่าง
# Import the required libraries
import os
# Define the location of the directory
path = r"C:/Users/Sairam/Documents/"
# Change the directory
os.chdir(path)
def read_files(file_path):
with open(file_path, 'r') as file:
print(file.read())
# Iterate over all the files in the directory
for file in os.listdir():
if file.endswith('.txt'):
# Create the filepath of particular file
file_path = f"{path}/{file}"
read_files(file_path)ผลลัพธ์
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 which resides across multiple computer devices, generally spread across locations or regions. Distributed ledger technology (DLT) includes blockchain technologies and smart contracts. While distributed ledgers existed prior to Bitcoin, the Bitcoin blockchain marks the convergence of a host of technologies, including timestamping of transactions, Peer-to-Peer (P2P) networks, cryptography, and shared computational power, along with a new consensus algorithm.
เรามีไฟล์ข้อความ 2 ไฟล์ในตำแหน่งที่ระบุ โปรแกรมอ่านเนื้อหาของไฟล์ทั้งสองและแสดงข้อความบนคอนโซล