📖 Python Cơ bản - Xử lý File và JSON
55 phút

Xử lý File và JSON trong Python

Đọc và ghi file text

Ghi file

# Ghi file mới
with open("data.txt", "w", encoding="utf-8") as file:
    file.write("Hello World!\n")
    file.write("Đây là dòng thứ hai\n")
    file.write("Dòng cuối cùng\n")

# Ghi thêm vào file
with open("data.txt", "a", encoding="utf-8") as file:
    file.write("Dòng được thêm vào cuối\n")

Đọc file

# Đọc toàn bộ file
with open("data.txt", "r", encoding="utf-8") as file:
    content = file.read()
    print(content)

# Đọc từng dòng
with open("data.txt", "r", encoding="utf-8") as file:
    for line in file:
        print(line.strip())  # strip() để bỏ ký tự xuống dòng

# Đọc thành list các dòng
with open("data.txt", "r", encoding="utf-8") as file:
    lines = file.readlines()
    print(lines)

Xử lý JSON

JSON sang Python

import json

# JSON string
json_string = '{"name": "John", "age": 30, "city": "New York"}'

# Chuyển JSON string thành Python dictionary
data = json.loads(json_string)
print(data["name"])  # John
print(data["age"])   # 30

Python sang JSON

import json

# Python dictionary
person = {
    "name": "John",
    "age": 30,
    "city": "New York",
    "is_student": False,
    "hobbies": ["reading", "swimming", "coding"]
}

# Chuyển thành JSON string
json_string = json.dumps(person, indent=2, ensure_ascii=False)
print(json_string)

Đọc và ghi file JSON

import json

# Ghi dictionary vào file JSON
data = {
    "students": [
        {"name": "Alice", "score": 85},
        {"name": "Bob", "score": 92},
        {"name": "Charlie", "score": 78}
    ]
}

with open("students.json", "w", encoding="utf-8") as file:
    json.dump(data, file, indent=2, ensure_ascii=False)

# Đọc file JSON
with open("students.json", "r", encoding="utf-8") as file:
    loaded_data = json.load(file)
    print(loaded_data["students"])

Xử lý lỗi

try:
    with open("nonexistent_file.txt", "r") as file:
        content = file.read()
except FileNotFoundError:
    print("File không tồn tại!")
except PermissionError:
    print("Không có quyền truy cập file!")
except Exception as e:
    print(f"Lỗi: {e}")

📝 Bài tập (1)

  1. Tạo ứng dụng quản lý todo list với file

Bài học "Xử lý File và JSON" - Khóa học "Python Cơ bản"