python读取索引
1)在Python文件处理中tell() (1) tell() in python file handling )
This method returns the current position of file pointer.
此方法返回文件指针的当前位置。
2)Python文件处理中的seek() (2) seek() in python file handling )
It set the position of file pointer at a specific position.
它将文件指针的位置设置在特定位置。
Syntax:
句法:
file_object.seek(offset, whence)
Here,
这里,
offset is the position of read/write pointer of the file.
offset是文件的读/写指针的位置。
whence is an optional argument, it has 3 values
whence是可选参数,它具有3个值
- 0 – to seek the file pointer from current position 0 –从当前位置查找文件指针
- 1 – to seek the file pointer from starting position of the file1 –从文件的起始位置查找文件指针
- 2 – to seek the file pointer from ending position of the file2 –从文件结束位置查找文件指针
Example:
例:
def main():
fo = open("data.txt","wt")
fo.write("Hello world, how are you? Here, you are learning python")
fo.close()
fo = open("data.txt","r")
print("Name of the File : ",fo.name)
str=fo.read(10)
print("Read String is till 10 : ",str)
pos= fo.tell()
print("Current Position : ",pos)
str=fo.read(10)
print("Read String is till next 10 : ",str)
pos= fo.tell()
print("Current Position : ",pos)
print()
print("Sending Pointer back to Top")
pos = fo.seek(0,0)
print("Current Position : ",pos)
str=fo.read(25)
print("Read String is till 25 : ",str)
pos= fo.tell()
print("Current Position : ",pos)
fo.close()
if __name__=="__main__":main()
Output
输出量
Name of the File : data.txt
Read String is till 10 : Hello worl
Current Position : 10
Read String is till next 10 : d, how are
Current Position : 20
Sending Pointer back to Top
Current Position : 0
Read String is till 25 : Hello world, how are you?
Current Position : 25
翻译自: https://www.includehelp.com/python/read-file-from-given-index-example-of-tell-and-seek.aspx
python读取索引