Notes & software courses · Free to learn
Aph's Blog
On this page

วันที่ 19 — การจัดการไฟล์ (File Handling)

👋 อ่านฟรีทั้งหมดบน Aph's Blog — เนื้อหาภาษาไทย ทำตามทีละหน้าใน sidebar ได้เลย หากมีข้อเสนอแนะหรืออยากให้เพิ่มหัวข้อไหน บอกได้เสมอ

เรียนรู้การอ่าน เขียน และจัดการไฟล์ประเภทต่าง ๆ ใน Python ตั้งแต่ TXT, JSON, CSV จนถึง XML

การจัดการไฟล์ (File Handling)

Python จัดการไฟล์ได้หลากหลาย ไฟล์ที่จะกล่าวถึง ได้แก่ text, json, csv, tsv และ xml ก่อนอื่นต้อง open ไฟล์ก่อน

การ Open ไฟล์เพื่ออ่าน

open() รับ mode เป็น argument: r = read (default), a = append, w = write, x = create ถ้าไม่ระบุ mode จะใช้ r โดยปริยาย

การอ่านด้วย read()

python
# syntax
open('filename', mode)
# mode
# 'r' = read,
# 'a'= append
# 'w' = write
# 'x' = create
# os
# 'b' = binary mode
# 't' = text mode (default)
python
f = open('./files/reading_file_example.txt')
print(f) # <_io.TextIOWrapper name='./files/reading_file_example.txt' mode='r' encoding='UTF-8'>
python
f = open('./files/reading_file_example.txt')
print(f.read()) # read the whole text
python
f = open('./files/reading_file_example.txt')
print(f.read(10)) # read the first 10 characters

การอ่านด้วย readline()

python
f = open('./files/reading_file_example.txt')
print(f.readline()) # read only the first line

การอ่านด้วย readlines()

python
f = open('./files/reading_file_example.txt')
print(f.readlines()) # read all the text line by line and return a list of lines

การอ่านด้วย splitlines()

python
f = open('./files/reading_file_example.txt')
lines = f.read().splitlines()
print(type(lines))
print(lines)

การใช้ with เพื่อ Close อัตโนมัติ

วิธีที่ดีกว่าคือใช้ with เพื่อให้ Python จัดการปิดไฟล์ให้อัตโนมัติ:

python
with open('./files/reading_file_example.txt') as f:
    lines = f.read().splitlines()
    print(type(lines))
    print(lines)

การ Open ไฟล์เพื่อเขียนและอัปเดต

การเพิ่มข้อมูล (Append)

ใช้ mode 'a' เพื่อเพิ่มข้อมูลต่อท้ายไฟล์ที่มีอยู่ หรือสร้างไฟล์ใหม่ถ้าไม่มี:

python
with open('./files/reading_file_example.txt','a') as f:
    f.write('This text has to be appended at the end')

การเขียน (Write)

ใช้ mode 'w' เพื่อเขียนทับไฟล์เดิมหรือสร้างไฟล์ใหม่:

python
with open('./files/writing_file_example.txt','w') as f:
    f.write('This text will be written in a newly created file')

การลบไฟล์

ใช้ os module เพื่อลบไฟล์:

python
import os
os.remove('./files/example.txt')

ควรตรวจสอบว่าไฟล์มีอยู่ก่อนลบเพื่อป้องกัน error:

python
import os
if os.path.exists('./files/example.txt'):
    os.remove('./files/example.txt')
else:
    print('The file does not exist')

ประเภทไฟล์

ไฟล์ TXT

ไฟล์ .txt คือรูปแบบที่ง่ายที่สุด ตัวอย่างข้างต้นเป็นตัวอย่างการทำงานกับ txt ไฟล์

ไฟล์ JSON

JSON (JavaScript Object Notation) เป็นรูปแบบข้อมูลที่ใช้กันอย่างแพร่หลาย Python มี json module สำหรับจัดการ:

python
# dictionary
person_dct= {
    "name":"Asabeneh",
    "country":"Finland",
    "city":"Helsinki",
    "skills":["JavaScrip", "React","Python"]
}
# json.dumps converts python dictionary to json string
json_string = json.dumps(person_dct)
print(type(json_string))
print(json_string)
python
import json
# JSON
person_json = '''
{
    "name": "Asabeneh",
    "country": "Finland",
    "city": "Helsinki",
    "skills": ["JavaScrip", "React", "Python"]
}'''
# let us change JSON to dictionary
person_dct = json.loads(person_json)
print(type(person_dct))
print(person_dct)
print(person_dct['name'])

การบันทึก JSON ลงไฟล์ด้วย json.dump():

python
import json
person = {
    "name": "Asabeneh",
    "country": "Finland",
    "city": "Helsinki",
    "skills": ["JavaScrip", "React", "Python"]
}
with open('./files/json_example.json', 'w', encoding='utf-8') as f:
    json.dump(person, f, ensure_ascii=False, indent=4)

ไฟล์ CSV

CSV (comma separated values) ใช้บันทึกข้อมูลตาราง Python มี csv module หรือใช้ pandas:

python
import csv
with open('./files/csv_example.csv') as f:
    csv_reader = csv.reader(f, delimiter=',')
    line_count = 0
    for row in csv_reader:
        if line_count == 0:
            print(f'Column names are {{", ".join(row)}}')
            line_count += 1
        else:
            print(
                f'\t{row[0]} is a teachers. He lives in {row[1]}, {row[2]}.')
            line_count += 1
    print(f'Number of lines:  {line_count}')

ไฟล์ XLSX

XLSX คือรูปแบบไฟล์ Excel ใช้ openpyxl หรือ xlrd ในการอ่าน:

python
import xlrd
excel_book = xlrd.open_workbook('sample.xls')
print(excel_book.nsheets)
print(excel_book.sheet_names())

ไฟล์ XML

XML คล้ายกับ HTML ใช้ xml.etree.ElementTree ในการ parse:

python
import xml.etree.ElementTree as ET
tree = ET.parse('./files/xml_example.xml')
root = tree.getroot()
print('Root tag:', root.tag)
print('Attribute:', root.attrib)
for child in root:
    print('field: ', child.tag)

💻 แบบฝึกหัด — วันที่ 19

ระดับ 1

  1. เขียน function ที่นับจำนวนบรรทัดและจำนวนคำในไฟล์ text — ไฟล์ทั้งหมดอยู่ในโฟลเดอร์ data:
    1) อ่านไฟล์ obama_speech.txt และนับจำนวนบรรทัดและคำ
    2) อ่านไฟล์ michelle_obama_speech.txt และนับจำนวนบรรทัดและคำ
    3) อ่านไฟล์ donald_speech.txt และนับจำนวนบรรทัดและคำ
    4) อ่านไฟล์ melina_trump_speech.txt และนับจำนวนบรรทัดและคำ
  2. อ่านไฟล์ countries_data.json ในโฟลเดอร์ data แล้วสร้าง function ที่หา 10 ภาษาที่มีคนพูดมากที่สุด
python
# ผลลัพธ์ควรมีลักษณะดังนี้
print(most_spoken_languages(filename='./data/countries_data.json', 10))
[(91, 'English'),
(45, 'French'),
(25, 'Arabic'),
(24, 'Spanish'),
(9, 'Russian'),
(9, 'Portuguese'),
(8, 'Dutch'),
(7, 'German'),
(5, 'Chinese'),
(4, 'Swahili'),
(4, 'Serbian')]

# ผลลัพธ์ควรมีลักษณะดังนี้
print(most_spoken_languages(filename='./data/countries_data.json', 3))
[(91, 'English'),
(45, 'French'),
(25, 'Arabic')]
  1. อ่านไฟล์ countries_data.json ในโฟลเดอร์ data แล้วสร้าง function ที่สร้าง list ของ 10 ประเทศที่มีประชากรมากที่สุด
python
# ผลลัพธ์ควรมีลักษณะดังนี้
print(most_populated_countries(filename='./data/countries_data.json', 10))

[
{'country': 'China', 'population': 1377422166},
{'country': 'India', 'population': 1295210000},
{'country': 'United States of America', 'population': 323947000},
{'country': 'Indonesia', 'population': 258705000},
{'country': 'Brazil', 'population': 206135893},
{'country': 'Pakistan', 'population': 194125062},
{'country': 'Nigeria', 'population': 186988000},
{'country': 'Bangladesh', 'population': 161006790},
{'country': 'Russian Federation', 'population': 146599183},
{'country': 'Japan', 'population': 126960000}
]

# ผลลัพธ์ควรมีลักษณะดังนี้
print(most_populated_countries(filename='./data/countries_data.json', 3))
[
{'country': 'China', 'population': 1377422166},
{'country': 'India', 'population': 1295210000},
{'country': 'United States of America', 'population': 323947000}
]

ระดับ 2

  1. แตก (extract) ที่อยู่อีเมลขาเข้าทั้งหมดเป็น list จากไฟล์ email_exchange_big.txt
  2. หาคำที่พบบ่อยที่สุดในภาษาอังกฤษ ตั้งชื่อ function ว่า find_most_common_words รับ parameter 2 ตัว ได้แก่ string หรือไฟล์ และจำนวนเต็มบวกที่ระบุจำนวนคำ function จะคืนค่า array ของ tuple เรียงลำดับจากมากไปน้อย
python
# ผลลัพธ์ควรมีลักษณะดังนี้
print(find_most_common_words('sample.txt', 10))
[(10, 'the'),
(8, 'be'),
(6, 'to'),
(6, 'of'),
(5, 'and'),
(4, 'a'),
(4, 'in'),
(3, 'that'),
(2, 'have'),
(2, 'I')]

# ผลลัพธ์ควรมีลักษณะดังนี้
print(find_most_common_words('sample.txt', 5))

[(10, 'the'),
(8, 'be'),
(6, 'to'),
(6, 'of'),
(5, 'and')]
  1. ใช้ function find_most_frequent_words เพื่อหา:
    1) 10 คำที่ปรากฏบ่อยที่สุดในสุนทรพจน์ของ Obama
    2) 10 คำที่ปรากฏบ่อยที่สุดในสุนทรพจน์ของ Michelle Obama
    3) 10 คำที่ปรากฏบ่อยที่สุดในสุนทรพจน์ของ Trump
    4) 10 คำที่ปรากฏบ่อยที่สุดในสุนทรพจน์ของ Melina Trump
  2. เขียน application Python ที่ตรวจสอบความคล้ายคลึงระหว่างข้อความ 2 ชิ้น รับ parameter เป็นไฟล์หรือ string แล้วประเมินความคล้ายคลึงของข้อความทั้งสอง เช่น ตรวจสอบความคล้ายคลึงระหว่างบทพูดของ Michelle กับ Melina อาจต้องใช้หลาย function ได้แก่ clean_text, remove_support_words และ check_text_similarity รายการ stop words อยู่ในโฟลเดอร์ data
  3. หา 10 คำที่ซ้ำมากที่สุดในไฟล์ romeo_and_juliet.txt
  4. อ่านไฟล์ hacker_news.csv แล้วหา:
    1) นับจำนวนบรรทัดที่มีคำว่า python หรือ Python
    2) นับจำนวนบรรทัดที่มีคำว่า JavaScript, javascript หรือ Javascript
    3) นับจำนวนบรรทัดที่มีคำว่า Java แต่ไม่มี JavaScript