Hướng dẫn how do i move a pointer to the end of a file in python? - làm cách nào để di chuyển con trỏ đến cuối tệp trong python?

Khi chúng tôi mở một tệp để đọc với Python (nghĩ rằng điều này đúng với bất kỳ làn đường lập trình nào), chúng tôi sẽ nhận được một fileHandle trỏ đến đầu tệp. Khi chúng tôi đọc từ tệp, con trỏ luôn chỉ đến nơi chúng tôi kết thúc việc đọc và lần đọc tiếp theo sẽ bắt đầu từ đó.

Đó là, trừ khi chúng tôi nói với FileHandle để di chuyển xung quanh.

Phương thức kể của FileHandle sẽ trả về vị trí hiện tại của con trỏ này.tell method of the filehandle will return the current location of this pointer.

Phương pháp tìm kiếm sẽ di chuyển con trỏ.seek method will move the pointer.

Trong ví dụ này, đầu tiên chúng tôi tạo một tệp và sau đó mở nó và đánh lừa với Tell và tìm kiếm không có lý do cụ thể chỉ để chỉ ra cách chúng hoạt động.tell and seek for no particular reason just to show how they work.

examples/python/seek.py

import os

filename = '/tmp/data.txt'
with open(filename, 'w') as fh:
    fh.write("Hello World!\nHow are you today?\nThank you!")

print(os.path.getsize(filename))  # 42

with open(filename) as fh:
    print(fh.tell())        # 0
    row = fh.readline()
    print(row)              # Hello World!
    print(fh.tell())        # 13

    fh.seek(-7, os.SEEK_CUR)
    print(fh.tell())        # 6

    row = fh.readline()
    print(row)              # World!
    print(fh.tell())        # 13

    fh.seek(0, os.SEEK_SET)
    print(fh.tell())        # 0
    print(fh.read(5))       # Hello

    fh.seek(-4, os.SEEK_END)
    print(fh.tell())        # 38
    print(fh.read())        # you!
    print(fh.tell())        # 42

Tìm kiếm có hai tham số. Lần đầu tiên nói có bao nhiêu byte để di chuyển (+ hoặc -) tham số thứ hai cho nó biết bắt đầu từ đâu. Trong một số trường hợp, cái trước được gọi là bù và cái sau được gọi là từ đâu. gets two parameters. The first says how many bytes to move (+ or -) the second parameter tells it where to start from. In some cases the former is called offset and the latter is called whence.

Từ đâu có thể là bất kỳ giá trị nào sau đây:whence can be any of the following values:

  • os.seek_set - bắt đầu của tệp
  • os.seek_cur - vị trí hiện tại
  • os.seek_end - kết thúc tệp

Một phần bù dương sẽ di chuyển con trỏ về phía trước, một phần bù âm sẽ di chuyển về phía sau.

Trường hợp đặc biệt

Có hai trường hợp đặc biệt:

fh.seek(0, os.SEEK_SET)  - go to the beginning of the file.
fh.seek(0, os.SEEK_END)  - go to the end of the file.



Sự mô tả

Phương thức tệp Python Seek () đặt vị trí hiện tại của tệp ở phần bù. Đối số từ là tùy chọn và mặc định là 0, có nghĩa là định vị tệp tuyệt đối, các giá trị khác là 1 có nghĩa là tìm kiếm liên quan đến vị trí hiện tại và 2 có nghĩa là tìm kiếm liên quan đến đầu của tệp.seek() sets the file's current position at the offset. The whence argument is optional and defaults to 0, which means absolute file positioning, other values are 1 which means seek relative to the current position and 2 means seek relative to the file's end.

Không có giá trị quay lại. Lưu ý rằng nếu tệp được mở để thêm bằng cách sử dụng 'A' hoặc 'A+', thì mọi hoạt động Seek () sẽ được hoàn tác ở lần ghi tiếp theo.

Nếu tệp chỉ được mở để viết ở chế độ phụ trợ bằng cách sử dụng 'A', phương thức này về cơ bản là không có op, nhưng nó vẫn hữu ích cho các tệp được mở ở chế độ phụ lục khi đọc được bật (chế độ 'A+').

Nếu tệp được mở ở chế độ văn bản bằng cách sử dụng 't', chỉ có độ lệch được trả về bởi Tell () là hợp pháp. Sử dụng các độ lệch khác gây ra hành vi không xác định.

Lưu ý rằng không phải tất cả các đối tượng tệp đều có thể tìm kiếm.

Cú pháp

Sau đây là Syntax for Seek () phương thức -seek() method −

fileObject.seek(offset[, whence])

Thông số

  • Offset - Đây là vị trí của con trỏ đọc/ghi trong tệp. − This is the position of the read/write pointer within the file.

  • từ đó - đây là tùy chọn và mặc định là 0 có nghĩa là định vị tệp tuyệt đối, các giá trị khác là 1 có nghĩa là tìm kiếm liên quan đến vị trí hiện tại và 2 có nghĩa là tìm kiếm so với đầu của tệp. − This is optional and defaults to 0 which means absolute file positioning, other values are 1 which means seek relative to the current position and 2 means seek relative to the file's end.

Giá trị trả về

Phương pháp này không trả về bất kỳ giá trị nào.

Thí dụ

Ví dụ sau đây cho thấy cách sử dụng phương thức Seek ().

Python is a great language
Python is a great language
#!/usr/bin/python

# Open a file
fo = open("foo.txt", "rw+")
print "Name of the file: ", fo.name

# Assuming file has following 5 lines
# This is 1st line
# This is 2nd line
# This is 3rd line
# This is 4th line
# This is 5th line

line = fo.readline()
print "Read Line: %s" % (line)

# Again set the pointer to the beginning
fo.seek(0, 0)
line = fo.readline()
print "Read Line: %s" % (line)

# Close opend file
fo.close()

Khi chúng tôi chạy trên chương trình, nó tạo ra kết quả sau -

Name of the file:  foo.txt
Read Line: Python is a great language.

Read Line: Python is a great language.

python_files_io.htm

Xem thảo luận

Cải thiện bài viết

Lưu bài viết

  • Đọc
  • Bàn luận
  • Xem thảo luận

    Cải thiện bài viết

    Lưu bài viết

    Đọc
     

    Bàn luận
     

    • Khái niệm xử lý tệp được sử dụng để lưu giữ dữ liệu hoặc thông tin được tạo sau khi chạy chương trình. Giống như các ngôn ngữ lập trình khác như C, C ++, Java, Python cũng hỗ trợ xử lý tệp. & NBSP;
       
    • Tham khảo bài viết dưới đây để hiểu những điều cơ bản của xử lý tệp. & NBSP; & NBSP;
       

    Xử lý tập tin trong Python. & NBSP; & nbsp;

    Đọc và ghi vào các tập tin trong Python & NBSP;change the position of the File Handle to a given specific position. File handle is like a cursor, which defines from where the data has to be read or written in the file. 
     

    tìm kiếm () phương thứcf.seek(offset, from_what), where f is file pointer
    Parameters: 
    Offset: Number of positions to move forward 
    from_what: It defines point of reference.
    Returns: Return the new absolute position.

    Trong Python, hàm Seek () được sử dụng để thay đổi vị trí của xử lý tệp thành một vị trí cụ thể nhất định. Tệp xử lý giống như một con trỏ, xác định từ nơi dữ liệu phải được đọc hoặc ghi trong tệp. & Nbsp; & nbsp;from_what argument. It accepts three values: 
     

    • Cú pháp: f.seek (offset, from_what), trong đó f là tập tin pulfparameter: & nbsp; offset: số lượng vị trí để di chuyển về phía trước & nbsp; from_what: nó xác định điểm tham chiếu. Returns: trả về vị trí tuyệt đối mới. sets the reference point at the beginning of the file 
       
    • Điểm tham chiếu được chọn bởi đối số từ_what. Nó chấp nhận ba giá trị: & nbsp; & nbsp; sets the reference point at the current file position 
       
    • 0: Đặt điểm tham chiếu ở đầu tệp & nbsp; & nbsp; sets the reference point at the end of the file 
       

    1: Đặt điểm tham chiếu tại vị trí tệp hiện tại & nbsp; & nbsp;
    Note: Reference point at current position / end of file cannot be set in text mode except when offset is equal to 0.
    Example 1: Let’s suppose we have to read a file named “GfG.txt” which contains the following text: 
     

    "Code is like humor. When you have to explain it, it’s bad."    

    Python3

    2: Đặt điểm tham chiếu ở cuối tệp & nbsp; & nbsp;

    fh.seek(0, os.SEEK_SET)  - go to the beginning of the file.
    
    8
    fh.seek(0, os.SEEK_SET)  - go to the beginning of the file.
    
    9
    fh.seek(0, os.SEEK_SET)  - go to the beginning of the file.
    
    7

    fh.seek(0, os.SEEK_END)  - go to the end of the file.
    
    1
    fh.seek(0, os.SEEK_END)  - go to the end of the file.
    
    2

    fh.seek(0, os.SEEK_END)  - go to the end of the file.
    
    1
    fh.seek(0, os.SEEK_END)  - go to the end of the file.
    
    4

    fh.seek(0, os.SEEK_END)  - go to the end of the file.
    
    5

    Output:

    20
    When you have to explain it, it’s bad.

    Theo mặc định, từ đối số được đặt thành 0.Note: điểm tham chiếu ở vị trí hiện tại / đầu của tệp không thể được đặt ở chế độ văn bản trừ khi độ lệch bằng 0. Ví dụ 1: giả sử chúng ta phải đọc một tệp có tên là GFG.TXT Có chứa văn bản sau: & nbsp; & nbsp;Seek() function with negative offset only works when file is opened in binary mode. Let’s suppose the binary file contains the following text.
     

    b'Code is like humor. When you have to explain it, its bad.'

    Python3

    Các

    fh.seek(0, os.SEEK_SET)  - go to the beginning of the file.
    
    8
    fileObject.seek(offset[, whence])
    
    5
    fileObject.seek(offset[, whence])
    
    6
    fh.seek(0, os.SEEK_SET)  - go to the beginning of the file.
    
    5
    fileObject.seek(offset[, whence])
    
    8
    fh.seek(0, os.SEEK_SET)  - go to the beginning of the file.
    
    7

    fh.seek(0, os.SEEK_END)  - go to the end of the file.
    
    1
    fh.seek(0, os.SEEK_END)  - go to the end of the file.
    
    2

    fh.seek(0, os.SEEK_END)  - go to the end of the file.
    
    1
    Python is a great language
    Python is a great language
    
    3
    Python is a great language
    Python is a great language
    
    4
    Python is a great language
    Python is a great language
    
    5

    fh.seek(0, os.SEEK_END)  - go to the end of the file.
    
    5


    Làm cách nào để di chuyển con trỏ sang dòng tiếp theo trong Python?

    Phương thức tệp python tiếp theo () Phương thức tệp python next () được sử dụng khi một tệp được sử dụng làm trình lặp, thường trong một vòng lặp, phương thức tiếp theo () được gọi là lặp đi lặp lại.Phương thức này trả về dòng đầu vào tiếp theo hoặc tăng sự ngăn chặn khi EOF bị nhấn. Python file method next() is used when a file is used as an iterator, typically in a loop, the next() method is called repeatedly. This method returns the next input line, or raises StopIteration when EOF is hit.

    Làm thế nào để bạn đến cuối một tập tin trong Python?

    Seek_set) - Đi đến đầu tệp.fh.seek (0, os.seek_end) - đi đến cuối tệp.fh. seek(0, os. SEEK_END) - go to the end of the file.

    Câu lệnh nào được sử dụng để di chuyển con trỏ trong một tệp đến cuối tệp?

    fseek () được sử dụng để di chuyển con trỏ tệp được liên kết với một tệp đã cho đến một vị trí cụ thể.Vị trí xác định điểm liên quan đến con trỏ tệp cần được di chuyển.Nó có ba giá trị: Seek_end: Nó biểu thị kết thúc của tệp. is used to move file pointer associated with a given file to a specific position. position defines the point with respect to which the file pointer needs to be moved. It has three values: SEEK_END : It denotes end of the file.

    Seek () làm gì trong Python?

    Phương thức Seek () đặt vị trí tệp hiện tại trong luồng tệp.sets the current file position in a file stream.