Python: File operations จัดการข้อมูลในไฟล์ แบบ…ไม่ได้โม้

Grassroot Engineer
4 min readApr 25, 2021

--

https://media.giphy.com/media/dVo6LGh09K9o1EsORR/giphy.gif

File handling (I/O) เป็นส่วนหนึ่งที่สำคัญของการทำ web application ในบทความนี้จะมาแนะนำวิธีการจัดการไฟล์และข้อมูลกันครับ

Python ได้ provide methods ไว้ใช้ในการอ่านเขียนข้อมูลเกี่ยกับไฟล์ไว้แล้วดังต่อไปนี้นะคับ

https://www.programiz.com/python-programming/file-operation

ในการจัดการข้อมูลในไฟล์จะมีลำดับขั้นตอนในการดำเนินการตามลำดับดังนี้

  1. Open a file
  2. Read or write (perform operation)
  3. Close the file

เริ่มกันเลย

1. Opening Files

เราจะใช้ฟังก์ชัน open() ในการเปิดไฟล์ ซึ่งฟังก์ชันนี้จะ return a file object ออกมา ซึ่งในการเปิดไฟล์แบบไม่ได้ระบุ mode (argument ตัวที่ 2) จะหมายถึง reading.

f = open('scores.txt')  # in current directory
f = open('/Users/atthana/Desktop/scores.txt') # in full path

นอกจากนี้ยังมี 4 modes เมื่อเราเปิด file ขั้นมาด้วยนั่นคือ

"r" - Read - Default value. Opens a file for reading, error if the file does not exist"a" - Append - Opens a file for appending, creates the file if it does not exist"w" - Write - Opens a file for writing, creates the file if it does not exist"x" - Create - Creates the specified file, returns an error if the file exists

นอกจากนี้ยังสามารถระบุได้ว่าเราจะจัดการไฟล์เป็น binary หรือ text

"t" - Text - Default value. open in Text mode"b" - Binary - open in Binary mode (e.g. images)"+" - pluse - Open a file for updating (reading and writing)

code ด้านล่างนี้จะเหมือนกับด้านบนเลยนะคับ เพียงแค่ระบุ mode ไปว่า เป็นการ read กับ text แต่ปกติ default มาแบบนี้อยู่แล้วจึงไม่จำเป็นต้องระบุเพิ่ม

f = open('scores.txt', 'rt)  # แบบนี้คือ default ทั้งหมดเลย ไม่ต้องใส่ rt ได้f = open("scores.txt",'w')  # write in text modef = open("img.bmp",'r+b')  # read and write in binary mode

ในการทำงานกับ file ใน text mode เราจำเป็นอย่างยิ่งที่จะต้องระบุ encoding ให้มันด้วย เพราะ
สุดท้ายใน argument ตัวที่ 3 จะมี endoing ให้เราระบุได้ด้วย เพราะ default encoding มันขึ้นกับ platform ด้วยเช่น Windows = cp1251, Linux = utf-8 เป็นต้น

f = open("scores.txt", mode='r', encoding='utf-8')

2. Closing Files in Python

เมื่อเราเปิดไฟล์ขึ้นมา และดำเนินการเสร็จแล้ว จำเป็นต้องปิดไฟล์นั้นไปด้วยโดยใช้ ฟังก์ชัน close() เนื่องจาก buffer นะคับ และการดำเนินการกับไฟล์อาจไม่ effect จนกระทั่งเราได้ปิดไฟล์นั้นก่อน

f = open('scores.txt', encoding= 'urf-8)  # in current directory# perform file operations

f.close() # แค่นี้คับ สำหรับการปิดไฟล์

แต่การปิดไฟล์ดื้อๆ เลย อาจไม่ปลอดภัยถ้ามี exception case เกิดขึ้น จึงควรเอา try มาครอบมันซะ ซึ่งจะมันใจได้ว่าไฟล์จะถูกปิดแน่นอน (finally) แม้ว่าจะ raised exception ขึ้นมาก็เถอะ

try:
f = open('scores.txt', 'rt') # in current directory
print(f.read())
finally:
f.close()

แต่วิธีที่ดีสุดเลยคือ ให้ใช้ with ดีกว่า ซึ่งแบบนี้จะมั่นใจได้ว่าไฟล์ถูกปิดเมื่อมันทำงานเสร็จ โดยไม่จำเป็นต้องเรียกใช้ close() มันจะปิดจากภายในเลย

with open('scores.txt', encoding='utf-8') as f:
print(f.read())

# perform file operations

3. Writing to Files in Python

เมื่อเราต้องการ write ไฟล์ เราจำเป็นต้องเปิดไฟล์ขึ้นมาด้วย mode “write” (w), “append” (a) หรือ “creation” (x)

"a" - Append - will append to the end of the file คือ เขียนเพิ่มในตอนท้าย

"w" - Write - will overwrite any existing content แบบนี้จะเขียนทับเลยนะ

ในการเขียนไฟล์ไปที่ไฟล์ที่มีอยุ่แล้ว (Existing file) เพื่อไม่ใช้มันไป override เราจะต้องใช้ mode ‘a’ นะคับ

เขียนไฟล์เพิ่มเติมเข้าไป โดยใช้ mode ‘a’ (Append)

ตรงกันข้าม ถ้าเราเขียนโดยใช้ mode ‘w’ จะทำให้ไป replace ทับของเดิมเลย
(ข้อมูลเดิมจะหายหมด อันนี้ต้อง awareไว้ด้วย)

เปลี่ยนจาก mode = ‘a’ เป็น mode = ‘w’ ซึ่งจะ override ข้อมูลทับไฟล์เดิมเลย

4. Create a new file (จะเหมือนกับ Writing to File)

เป็นการสร้างไฟล์ใหม่ขึ้นมาซึ่งมี mode ห้เลือกใช้งานดังนี้

"x" - Create - will create a file, returns an error if the file exist
mode นี้จะแจ้งเตือนด้วยถ้ามีไฟล์ชื่อนั้นแล้ว

"a" - Append - will create a file if the specified file does not exist

"w" - Write - will create a file if the specified file does not exist
ถ้ามีไฟล์แล้วก็จะเขียนทับไฟล์เดิมเลย

ภาพแสดงการเปรียบเทียบ creating a new file แบบต่างๆ

5. Reading Files in Python

ในการอ่านไฟล์ เราจะต้อง open file ด้วย mode ‘r’ นะ ซึ่งจริงๆก็คือ default อยู่แล้ว
ในการใช้ read() แค่นี้จะ return text ทั้งหมดของไฟล์ออกมาเลย

read() จะอ่านค่าออกมาทั้งไฟล์เลย

เราสามารถกำหนด int เข้าไปภายใน read() ได้เพื่อให้อ่านทีละ digit เลย

กำหนดให้อ่านค่าเป็น digit เลย

การอ่านค่าจากไฟล์โดยใช้ for-loop ซึ่งวิธีนี้ไม่ต้องใช้ read() แค่เพียง open() ไฟล์ขึ้นมาเท่านั้น

การ read แบบ line by line ด้วย for-loop วิธีนี้ก็มีประสิทธิภาพและเร็ว โดยใช้ end=’’ ไม่งั้นจะจบด้วย \n แทนซึ่งไม่ตรงกับข้อมูลจริง

นอกจากนี้ยังมีลูกเล่นจาก methods ในการจัดการอีก เช่น

"tell()" - เมื่อต้องการรู้ว่าตอนนี้ position ของ cursor ที่ใช้อ่านอยู่ตำแหน่งไหน
(get the current file position)

"seek(0)" - เมื่อต้องการนำ cursor ที่ใช้อ่าน ให้ไปอยู่ที่ตำแหน่งตั้งต้นเหมือนเดิม
(bring file cursor to initial position)

การใช้ tell() และ seek() เพื่อ get postion และ bring cursor ในไฟล์

สุดท้ายนอกจาก read() ที่เป็นการอ่านทั้งหมด ยังสามารถให้อ่านเป็นบรรทัดได้ โดยอ่านแบบ individual lines of a file

read()= read and return the entire file or up to the number of bytes if specified

readline()= read a file until the new line, including the newline character and return a single line or up to the number of bytes if specified

readlines()= returns a list of remaining lines of the entire file. All these reading methods return empty values when the end of file (EOF) is reached.

readline() และ readlines() กับผลลัพธ์ที่ได้

6. Delete a File

สุดท้ายคือการ delete file นะคับ
การลบไฟล์จะใช้ lib ของ os

การลบ file และการลบ directory

import os
if os.path.exists("scores.txt"):
os.remove("scores.txt")
else:
print("The file does not exist")
import os
os.rmdir("myFolder")
Python Delete Files.

แล้วพบกันใหม่คับ

--

--

Grassroot Engineer
Grassroot Engineer

Written by Grassroot Engineer

ATM engineer who is interested in CODING and believe in EFFORT. — https://grassrootengineer.com

No responses yet