且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

只读取 .txt 文件中的最后一个字符

更新时间:2023-11-17 18:26:22

从文件中读取最后一个字符:

Reading the last character from a file:

with open(filename, 'rb+') as f:
    f.seek(f.tell()-1,2)    # f.seek(0,2) is legal for last char in both python 2 and 3 though
    print f.read()

对于 Python 3
为了使它更通用,我们想在不打开二进制模式的情况下读取文件的倒数第二个(可以是任何字符):

For Python 3
To make it more generic say we want to read second last (can be any though) char of the file without turning on the binary mode:

with open('file.txt', 'r') as f:
    f.seek(0, 2)
    # seek to end of file; f.seek(0, os.SEEK_END) is legal

    f.seek(f.tell() - 2, 0)
    # seek to the second last char of file;
    # while f.seek(f.tell()-2, os.SEEK_SET) is legal,
    # f.seek(-2, 0) will throw an error.

    print(f.read())

seek 是一个文件对象处理注释

Seek is a file object handling comment

file.seek(offset,position)

  1. offset:您需要多少个字符(即 1 表示一个字符)
  2. position:告诉你的文件读/写操作应该从哪里开始.
    • 0 表示文件开始
    • 1 表示文件读/写光标的当前位置
    • 2 表示文件结束
  1. offset: How many characters you need (i.e. 1 means one character)
  2. position: Tell where your file read/write operation should start .
    • 0 means starting of file
    • 1 means current position of file read/write cursor
    • 2 means end of file

f.seek(f.tell()-1,2) 表示到文件末尾并往回遍历一个元素

f.seek(f.tell()-1,2) means go to the end of file and traverse back one element

print f.read() 打印从seek命令获得的值

print f.read() prints the value obtained from the seek command