Python – Files

Trong phần này của Python, chúng ta làm việc với file và standard input/output. Chúng ta tìm hiểu cách đọc/ghi file.

Mọi thứ trong Python là object. Mọi thứ trong UNIX là file.

Hàm open file

open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None)

– file: tên file (chứa cả đường dẫn) được open.
– mode: chỉ ra open file như thế nào (để đọc/ghi/update)
– encoding: tên encoding được dùng để decode/encode file
– errors: chỉ ra cách xử lí encoding/decoding erros
– newline: control behavior của kí tự xuống dòng

Bảng mode

Mode Meaning
‘r’ Reading (default)
‘w’ Writing
‘a’ Appending
‘b’ Binary data
‘+’ Updating (reading & writing)
‘x’ Tạo file mới, nếu file đã tồn tại báo lỗi

Ví dụ 1: file test.txt là file dạng text

This is test file
Today is 18/5/2022
I'm Python beginner

Câu lệnh with

Làm việc với nhiều file có thể thường bị lỗi, do đó, chúng ta phải quản lí exception. Ngoài ra, file object phải được close khi file object ko dùng nữa. Câu lệnh with đơn giản hóa việc xử lí exception bởi việc gói gọn các công đoạn chuẩn bị và clean task. Nó sẽ tự động close file.

Ví dụ 2: Sử dụng câu lệnh with

with open('test.txt', 'r') as f:

    contents = f.read()
    print(contents)

Đoạn code này đọc nội dung trong file test.txt.

with open('test.txt', 'r') as f:

Với hàm open(), chúng ta mở file test.txt và đọc file. file object được ánh xạ cho f. Câu lệnh with đảm nhận việc xử lí exception và close file.

contents = f.read()

Hàm read() đọc toàn bộ nội dung file test.txt cho đến khi gặp EOF (End Of File). Hàm read() trả về data đọc được theo kiểu string.

Kết quả:
C:\Users\Dell>python test.py
This is test file
Today is 18/5/2022
I’m Python beginner

Hàm đọc file

Hàm read() đọc số lượng file theo tham số truyền vào. Nếu không chỉ định số lượng, hàm read() đọc toàn bộ file.
Ví dụ 3: Đọc một số byte trong file

import sys

with open('test.txt', 'r') as f:

    print(f.read(5))
    print(f.read(9))

Trong ví dụ này, đọc 5 kí tự rồi in ra màn hình console. Sau đó, đọc tiếp 9 byte tiếp theo và in ra màn hình console.

Kết quả:
C:\Users\Dell>python test.py
This
is test f

Hàm get vị trí trong file

Vị trí trong file là vị trí từ nơi chúng ta đọc data từ file. Hàm tell() trả về vị trí hiện tại trong file và hàm seek() dịch chuyển vị trí trong file
Ví dụ 4: Get vị trí trong file

with open('test.txt', 'r') as f:

    print(f.read(14))
    print(f"The current file position is {f.tell()}")

    f.seek(0, 0)

    print(f.read(30))

Trong ví dụ, chúng ta đọc 14 byte và in ra vị trí file hiện tại. Tiếp theo, chúng ta move vị trí file hiện tại về đầu file bằng hàm seek() và đọc 30 byte.

Kết quả:
C:\Users\Dell>python test.py
This is test f
The current file position is 14
This is test file
Today is 18/

Hàm readline

Hàm readine() đọc 1 dòng trong file.
Ví dụ 5: Đọc từng dòng trong file

with open('test.txt', 'r') as f:

    while True:

        line = f.readline()

        if not line:
            break

        else:
            print(line.rstrip())

Hàm readline đặc trong vòng loop => đọc từng dòng cho đến khi kết thúc file.

while True:

Đây là vòng lặp vô hạn, muốn thoát khỏi vòng lặp vô hạn cần từ khóa break.

line = f.readline()

Nội dung từng dòng được lưu vào biến line. Biến line chứa cả kí tự newline (kí tự xuống dòng)

if not line:
    break

else:
    print(line.rstrip())

Chúng ta gọi lệnh break nếu gặp EOF (End Of File), ngược lại, chúng ta in nội dung từng line ra màn hình console.
line.rstrip() remove kí tự newline ở cuỗi chuỗi.

Kết quả:
C:\Users\Dell>python test.py
This is test file
Today is 18/5/2022
I’m Python beginner

Trong ví dụ sau, chúng ta sử dụng 1 cách thuận tiện hơn để duyệt qua các line trong file
Ví dụ 6: Đọc file với keyword with

with open('test.txt', 'r') as f:
    for line in f:
        print(line.rstrip())

File object là interator. Chúng ta có thể truyền file object vào vòng lặp for và duyệt từng dòng.
Kết quả:
C:\Users\Dell>python test.py
This is test file
Today is 18/5/2022
I’m Python beginner

Hàm readlines

Hàm readlines đọc dữ liệu cho đến khi kết thúc file và trả về list dòng dữ liệu
Ví dụ 7: Đọc toàn bộ file sử dụng hàm readlines

with open('test.txt', 'r') as f:

    contents = f.readlines()
    for i in contents:
        print(i.strip())

Hàm readlines đọc tất cả nội dung của file và lưu vào memory. Nếu kích thước file lớn => có thể gây lỗi khi đọc file.
Kết quả:
C:\Users\Dell>python test.py
This is test file
Today is 18/5/2022
I’m Python beginner

Hàm write file

Hàm write ghi string vào file.
Ví dụ 9: Ghi file sử dụng hàm write()

text = '''Today is 28/5/2022, 
I don't want to do anything because I'm tired\n'''

with open('data.txt', 'w') as f:

    f.write(text)

Open file với mode ‘w’ để ghi file. Nếu file không tồn tại, file mới sẽ được tạo. Nếu file đã tồn tại, nội dung bị ghi đè.
Kết quả: data.txt
Today is 28/5/2022,
I don’t want to do anything because I’m tired

Standard I/O

Có 3 loại I/O connection: standard input, standard output và standard error.
– Standard input là dữ liệu truyền vào chương trình thông qua keyboard.
– Standard output là nơi chúng ta in dữ liệu với keyword print
– Standard error là nơi chương trình in ra error message.

Standard input và output trong Python thường là các object trong module sys.

Object Mô tả
sys.stdin Standard input
sys.stdout Standard output
sys.stderr Standard error

Python Standard input

Standard input là dữ liệu truyền vào chương trình
Ví dụ 10: Nhập dữ liệu từ keyboard

import sys

print('Enter your name: ', end='')

name = ''

sys.stdout.flush()

while True:

    c = sys.stdin.read(1)

    if c == '\n':
        break

    name = name + c

print('Your name is:', name)

Hàm read() đọc 1 kí tự từ standard input. Trong ví dụ này, chúng ta in ra dòng hướng dẫn “Enter your name”. Chúng ra nhập tên và press enter. Enter tạo ra kí tự xuống dòng ‘\n’

Kết quả:
C:\Users\Dell>python test.py
Enter your name: vu hong viet
Your name is: vu hong viet

Để lấy dữ liệu input, chúng ta có thể sử dụng function: input và raw_input.
Ví dụ 11: Sử dụng input() để nhập dữ liệu từ keyboard

data = input('Enter value: ')

print('You have entered:', data)

Kết quả:
C:\Users\Dell>python test.py
Enter value: viet
You have entered: viet

Python standard output

Standard output là nơi chúng ta in ra dữ liệu
Ví dụ 12: in ra màn hình console string

import sys

sys.stdout.write('Hello world\n')

Ví dụ này in ra standard output (console terminal) string.
Sử dụng hàm write() để in string ra màn hình
Kết quả:
C:\Users\Dell>python test.py
Hello world

Sử dụng hàm print() để in string vào sys.stdout
Ví dụ 13: Sử dụng hàm print() để in string vào sys.stdout

print('Hello world')
print('Python', 'JS', 'C/C++', 'Java', sep=":")

vals = [1, 2, 3, 4, 5]

for e in vals:
    print(e, end=' ')

print()

Trong ví dụ này, chúng ta sử dụng thêm parameter sep và end trong hàm print().
– Parameter sep = “:” phân tách các string bởi dấu :
– Parameter end = ” ” thêm kí tự space vào cuối chuỗi

Kết quả:
C:\Users\Dell>python test.py
Hello world
Python:JS:C/C++:Java
1 2 3 4 5

Có thể sử dụng hàm print() để ghi string ra file. Hàm print() bao gồm parameter file, chỉ định nơi ghi dữ liệu
Ví dụ 14: Sử dụng print() để ghi dữ liệu ra file

with open('test.txt', 'w') as f:

    print('Python', file=f)
    print('JS', file=f)
    print('C/C++', file=f)
    print('Java', file=f)
    print('Top popular language', file=f)

Parameter file được truyền vào hàm print(), ám chỉ việc ghi vào file.

Kết quả: test.txt
Python
JS
C/C++
Java
Top popular language

Python redirection

Standard output có thể được redirect. Trong ví dụ dưới đây, chúng ta có thể redirect standard output vào regular file.
Ví dụ 15: switch standard output từ file sang console terminal

import sys

with open('output.txt', 'w') as f:

    sys.stdout = f

    print('Write file start')
    sys.stdout.write('Python\n')
    sys.stdout.writelines(['C++\n', 'Java\n'])

    sys.stdout = sys.__stdout__

    print('Write on console')
    sys.stdout.write('Python, C++, Java\n')

Trong ví dụ này, chúng ta switch từ standard ouput sang file

sys.stdout = f

Sau đó, chúng ta restore lại standard output

sys.stdout = sys.__stdout__

Kết quả:
C:\Users\Dell>python test.py
Write on console
Python, C++, Java

output.txt
Write file start
Python
C++
Java

Module pickle

Cho đến nay, chúng ta đang làm việc với dữ liệu dạng văn bản đơn giản. Điều gì sẽ xảy ra nếu chúng ta đang làm việc với các object? Đối với những tình huống như vậy, chúng ta có thể sử dụng pickle module. Module này chia nhỏ các object Python. Các object Python được chuyển đổi thành các chuỗi byte và được ghi vào các tệp văn bản. Quá trình này được gọi là pickling (nén). Thao tác nghịch đảo, đọc từ file và tái tạo lại các object được gọi là unpickling (giải nén).

Ví dụ 16:

import pickle


class Person:

    def __init__(self, name, age):
        self.name = name
        self.age = age

    def get_name(self):
        return self.name

    def get_age(self):
        return self.age


person = Person('Monica', 15)
print(person.get_name())
print(person.get_age())

with open('monica', 'wb') as f:
    pickle.dump(person, f)

with open('monica', 'rb') as f2:
    monica = pickle.load(f2)

print(monica.get_name())
print(monica.get_age())

Trong ví dụ này, chúng ta define class Person. Chúng ta tạo 1 persion, băm object sử dụng hàm dump(), dữ liệu băm được lưu vào fiel monica. Chúng ta close file và đọc file monica, giải nén object sử dụng hàm load().

Kết quả:
C:\Users\Dell>python test.py
Monica
15
Monica
15

Be the first to comment

Leave a Reply