📌  相关文章
📜  Python告诉()函数

📅  最后修改于: 2022-05-13 01:55:43.620000             🧑  作者: Mango

Python告诉()函数

Python也支持文件处理并提供用于创建、写入和读取文件的内置函数。在Python中可以处理两种类型的文件,普通文本文件和二进制文件(用二进制语言编写,0s 和 1s)。

  • 文本文件:在这种类型的文件中,每一行文本都以一个叫做 EOL(End of Line)的特殊字符结束,在Python中默认是字符('\n')。
  • 二进制文件:在这种类型的文件中,行没有终止符,数据在转换成机器可以理解的二进制语言后存储。

告诉()方法:

访问模式控制打开文件中可能的操作类型。它指的是文件打开后将如何使用。这些模式还定义了文件句柄在文件中的位置。文件句柄就像一个游标,它定义了必须从哪里读取或写入文件中的数据。有时了解文件句柄的位置对我们来说很重要。 tell() 方法可用于获取文件句柄的位置。 tell() 方法返回文件对象的当前位置。此方法不接受任何参数并返回一个整数值。最初文件指针指向文件的开头(如果没有以附加模式打开)。所以,tell() 的初始值为零。
句法 :

file_object.tell()

假设名为“myfile”的文本文件如下所示:

蟒蛇告诉()

# 示例1:文件句柄在读取或写入文件之前的位置。

Python3
# Python program to demonstrate
# tell() method
  
  
# Open the file in read mode
fp = open("myfile.txt", "r")
  
# Print the position of handle
print(fp.tell())
  
#Closing file
fp.close()


Python3
# Python program to demonstrate
# tell() method
  
# Opening file
fp = open("sample.txt", "r")
fp.read(8)
  
# Print the position of handle
print(fp.tell())
  
# Closing file
fp.close()


Python3
# Python program to demonstrate
# tell() method
  
# for reading binary file we
# have to use "wb" in file mode.
fp = open("sample2.txt", "wb")
print(fp.tell())
  
# Writing to file
fp.write(b'1010101')
  
print(fp.tell())
  
# Closing file
fp.close()


输出 :

0

# 示例2:从文件中读取数据后文件句柄的位置。

Python3

# Python program to demonstrate
# tell() method
  
# Opening file
fp = open("sample.txt", "r")
fp.read(8)
  
# Print the position of handle
print(fp.tell())
  
# Closing file
fp.close()

输出 :

8

# 示例 3:对于二进制文件。让我们创建一个二进制文件,我们会在写入二进制文件之前和之后注意句柄的位置。

Python3

# Python program to demonstrate
# tell() method
  
# for reading binary file we
# have to use "wb" in file mode.
fp = open("sample2.txt", "wb")
print(fp.tell())
  
# Writing to file
fp.write(b'1010101')
  
print(fp.tell())
  
# Closing file
fp.close()

输出 :

0
7