Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Python - Ghi dữ liệu nhiều file vào file master


Xử lý file là phần quan trọng của ứng dụng web. Python cung cấp nhiều hàm để tạo, đọc, cập nhật, xóa file.

Để ghi vào file hiện có, thêm tham số cho hàm open():

  • "a" - Append: ghi thêm vào cuối file.
  • "w" - Write: ghi đè nội dung hiện có.

Ví dụ: Gộp nhiều file dữ liệu thành file master

import os

# Liệt kê file trong thư mục dữ liệu
data_dir = r'D:\python\data_files\data_files'
target_dir = r'D:\python\data_files\target_file'
out_file = r'D:\python\data_files\target_file\master.txt'

lis = os.listdir(data_dir)
print('Files:', lis)

# Xóa file master cũ nếu tồn tại
if os.path.exists(out_file):
    os.remove(out_file)

# Ghi header
with open(out_file, 'a', encoding='utf-8') as f:
    f.write('empno, ename, sal\n')

# Gộp nội dung các file
for filename in lis:
    filepath = os.path.join(data_dir, filename)
    with open(filepath, 'r', encoding='utf-8') as infile:
        lines = infile.readlines()
    with open(out_file, 'a', encoding='utf-8') as outfile:
        for line in lines:
            outfile.write(line)

# Cách 2: Sử dụng pandas
import pandas as pd
df1 = pd.read_csv(r'D:\python\data_files\data_files\emp_1.txt')
df2 = pd.read_csv(r'D:\python\data_files\data_files\emp_2.txt')
df3 = pd.read_csv(r'D:\python\data_files\data_files\emp_3.txt')
result = pd.concat([df1, df2, df3])
result.to_csv(out_file, encoding='utf-8', index=False)

Giải thích

  • Cách 1: Dùng I/O file cơ bản, phù hợp file text đơn giản.
  • Cách 2: Dùng pandas, mạnh mẽ hơn với CSV, hỗ trợ xử lý dữ liệu phức tạp.