การจัดการข้อมูล และการบันทึกข้อมูลแบบไฟล์ CSV
ในส่วนการเก็บหรือบันทึกข้อมูล ในระบบควบคุมอัตโนมัติหรือในเครื่องจักรต่างๆ มักจะนิยมใช้การเก็บข้อมูลด้วยไฟล์ CSV ย่อมาจาก "A Comma-Separated Values" แปลว่าไฟล์ค่าที่มีเครื่องหมายจุลภาคคั่นในแต่ละบรรทัด ซึ่งมีข้อดีหลายประการคือ ไฟล์ที่ได้มีขนาดเล็กมาก รองรับการใช้งานกับโปรแกรมฐานข้อมูลต่างๆ รวมทั้ง Microsoft Excel รองรับการเปิดไฟล์ด้วยโปรแกรม Text Editor รวมทั้ง Microsoft Word ในการพัฒนาระบบจัดเก็บข้อมูลอัตโนมัติจะเริ่มต้นจากขั้นตอนของการการสร้างโฟลเดอร์ ซึ่งมีขั้นตอนดังต่อไปนี้
การสร้างโฟลเดอร์ด้วย module os มีรูปแบบดังนี้
import os
def Make_folder(directory):
try:
if not os.path.exists(directory):
os.makedirs(directory)
except OSError:
print('Error: Create Disrectory. ' + directory)
Make_folder(r'D:\Logfile1\11.02.2025')
การเขียนโปรแกรมบน Python แสดงตามภาพด้านล่าง
การตรวจสอบโฟลเดอร์ใน path ด้วย module os และ module glob มีรูปแบบดังนี้
import glob
import os
# Get all files and folders in the directory
folder_log = glob.glob(r'D:\Logfile\*')
# Extract only the folder or file names
folder_names = [os.path.basename(path) for path in folder_log]
print(folder_names)
การเขียนโปรแกรมบน Python แสดงตามภาพด้านล่าง
การนับจำนวนข้อมูลในโฟรเดอร์ด้วย module os และ module glob มีรูปแบบดังนี้
import glob
import os
folder_log = glob.glob(r'D:\Logfile\*')
folder_names = [os.path.basename(path) for path in folder_log]
num_files = len(folder_names)
print(folder_names)
print(num_files)
การเขียนโปรแกรมบน Python แสดงตามภาพด้านล่าง
การกำหนดชื่อโฟล์เดอร์เป็น วัน-เดือน-ปี มีรูปแบบดังนี้
การแสดง วัน-เดือน-ปี ของระบบปฏิบัติการ
from datetime import datetime
now = datetime.now()
formatted_date = now.strftime('%d.%m.%Y')
print("Formatted Date:", formatted_date)
การเขียนโปรแกรมบน Python แสดงตามภาพด้านล่าง
การนับจำนวนข้อมูลในโฟรเดอร์ด้วย module os และ module glob มีรูปแบบดังนี้
import os
from datetime import datetime
def Make_folder(directory):
try:
if not os.path.exists(directory):
os.makedirs(directory)
print(f"Created directory: {directory}")
except OSError as e:
print(f'Error: Create Directory. {directory} - {e}')
# Get the current date and format it
now = datetime.now()
formatted_date = now.strftime('%d.%m.%Y')
print("Formatted Date:", formatted_date)
# Define the base path and folder name
path = r'D:\Logfile'
folder_name = formatted_date
# Check if the folder exists
found = False
for root, dirs, _ in os.walk(path):
if folder_name in dirs:
print(f"The folder '{folder_name}' exists in '{root}'.")
found = True
break
# If the folder does not exist, create it in a new location
if not found:
new_folder_path = os.path.join(r'D:\Logfile', folder_name) # Properly concatenate paths
Make_folder(new_folder_path)
print(f"Create new folder")
การเขียนโปรแกรมบน Python แสดงตามภาพด้านล่าง