Xử lý file trong Python: Hướng dẫn chi tiết

 


Xử lý file trong Python: Hướng dẫn chi tiết

Xử lý file là một kỹ năng quan trọng trong lập trình Python, giúp đọc, ghi và quản lý dữ liệu một cách hiệu quả. Trong bài viết này, chúng ta sẽ tìm hiểu về cách làm việc với file văn bản, file CSV và JSON.

1. Đọc và ghi file văn bản (open, read, write)

Mở file trong Python

Python sử dụng hàm open() để mở file. Cú pháp:

file = open("filename.txt", "mode")

Trong đó mode có thể là:

  • 'r' – Mở file để đọc (mặc định).
  • 'w' – Mở file để ghi (nếu file đã tồn tại, nội dung sẽ bị ghi đè).
  • 'a' – Mở file để ghi, thêm vào cuối file (không ghi đè).
  • 'b' – Mở file ở chế độ nhị phân (dùng với hình ảnh, file PDF...)

Đọc file

  • Đọc toàn bộ nội dung file:
with open("example.txt", "r") as file: content = file.read() print(content)
  • Đọc từng dòng:
with open("example.txt", "r") as file: for line in file: print(line.strip())
  • Đọc n ký tự đầu tiên:
with open("example.txt", "r") as file: content = file.read(10) # Đọc 10 ký tự đầu tiên print(content)

Ghi file

  • Ghi đè nội dung file:
with open("example.txt", "w") as file: file.write("Hello, Python!\n")
  • Ghi thêm nội dung vào file:
with open("example.txt", "a") as file: file.write("This is an appended line.\n")

2. Xử lý file CSV trong Python

CSV (Comma-Separated Values) là định dạng phổ biến để lưu trữ dữ liệu bảng.

Đọc file CSV

Python có module csv giúp làm việc với file CSV dễ dàng:

import csv with open("data.csv", "r") as file: reader = csv.reader(file) for row in reader: print(row)
  • Đọc file CSV dưới dạng từ điển:
with open("data.csv", "r") as file: reader = csv.DictReader(file) for row in reader: print(row["name"], row["age"]) # Giả sử có cột "name" và "age"

Ghi file CSV

  • Ghi danh sách vào file CSV:
with open("output.csv", "w", newline='') as file: writer = csv.writer(file) writer.writerow(["Name", "Age"]) writer.writerow(["Alice", 25]) writer.writerow(["Bob", 30])
  • Ghi từ điển vào file CSV:
with open("output.csv", "w", newline='') as file: fieldnames = ["name", "age"] writer = csv.DictWriter(file, fieldnames=fieldnames) writer.writeheader() writer.writerow({"name": "Alice", "age": 25}) writer.writerow({"name": "Bob", "age": 30})

3. Xử lý file JSON trong Python

JSON (JavaScript Object Notation) là định dạng phổ biến để trao đổi dữ liệu.

Đọc file JSON

Python có module json để xử lý JSON:

import json with open("data.json", "r") as file: data = json.load(file) print(data)

Ghi file JSON

  • Ghi dữ liệu vào file JSON:
data = {"name": "Alice", "age": 25} with open("output.json", "w") as file: json.dump(data, file, indent=4)

Kết luận

Việc xử lý file văn bản, CSV và JSON trong Python là rất quan trọng khi làm việc với dữ liệu. Bằng cách nắm vững các thao tác này, bạn có thể dễ dàng đọc, ghi và quản lý dữ liệu hiệu quả. Hy vọng bài viết này giúp bạn làm chủ kỹ năng xử lý file trong Python!

Mới hơn Cũ hơn
Đọc tiếp:
Lên đầu trang