Home  >  Article  >  Backend Development  >  What is python file positioning? What is the role of file positioning?

What is python file positioning? What is the role of file positioning?

乌拉乌拉~
乌拉乌拉~Original
2018-08-17 14:45:592701browse

In the python learning link of today’s article, let’s learn about the Python file positioning. In the next article, I will tell my friends what file positioning in python is and what this file positioning can do.

File positioning

The tell() method tells you the current position in the file. In other words, the next read and write will occur so many bytes from the beginning of the file. after.

seek(offset [,from]) method changes the position of the current file. The Offset variable represents the number of bytes to be moved. The From variable specifies the reference position from which to start moving bytes.

If from is set to 0, this means that the beginning of the file is used as the reference position for moving bytes. If set to 1, the current position is used as the reference position. If it is set to 2, then the end of the file will be used as the reference position.

Example:

# !/usr/bin/python
# -*- coding: UTF-8 -*-
# 打开一个文件
fo = open("foo.txt", "r+")
str = fo.read(10)
print "读取的字符串是 : ", str
# 查找当前位置
position = fo.tell()
print "当前文件位置 : ", position
# 把指针再次重新定位到文件开头
position = fo.seek(0, 0)
str = fo.read(10)
print "重新读取字符串 : ", str
# 关闭打开的文件
fo.close()

The output result of the above example:

读取的字符串是 :  This is te
当前文件位置 :  10
重新读取字符串 :  This is te

The above is all the content of this article. I hope what I said and the examples I gave can be helpful to you.

For more related knowledge, please visit the Python tutorial column on the php Chinese website.

The above is the detailed content of What is python file positioning? What is the role of file positioning?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn