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

Cách dùng seek() reset vị trí đọc/ghi file Python?


Dùng phương thức seek(offset[, whence]). Thiết lập vị trí hiện tại file, như stdio fseek(). whence tùy chọn mặc định 0 (absolute positioning); 1 (relative current), 2 (relative end).

Ví dụ

File đã mở, quay về đầu:

f = open('my_file.txt', 'r')
f.seek(0)
f.close()

Con trỏ về đầu file. Tham số 2 đưa con trỏ về cuối file.