python 示例_带有示例的Python File seek()方法

落日映苍穹つ 2023-03-05 12:44 197阅读 0赞

python 示例

文件seek()方法 (File seek() Method)

seek() method is an inbuilt method in Python, it is used to set the current file position (or file pointer).

seek()方法是Python中的内置方法,用于设置当前文件位置(或文件指针)。

Syntax:

句法:

  1. file_object.seek(offset)

Parameter(s):

参数:

  • offset – It specifies the offset to sets the current file location.

    offset –指定用于设置当前文件位置的偏移量。

Return value:

返回值:

The return type of this method is , it returns the new file position.

该方法的返回类型为 ,它返回新文件的位置。

Example:

例:

  1. # Python File seek() Method with Example
  2. # creating a file
  3. myfile = open("hello.txt", "w")
  4. # writing to the file
  5. res = myfile.write("Hello friends, how are you?")
  6. print(res, "bytes written to the file.")
  7. # closing the file
  8. myfile.close()
  9. # reading content from the file
  10. myfile = open("hello.txt", "r")
  11. print("file content...")
  12. print(myfile.read())
  13. # sets the current file location to 6
  14. print("file content from 6th position...")
  15. myfile.seek(6)
  16. print(myfile.read())
  17. # sets the current file location to 0
  18. print("file content from 0th position...")
  19. myfile.seek(0)
  20. print(myfile.read())
  21. # sets the current file location to 12
  22. print("file content from 12th position...")
  23. myfile.seek(12)
  24. print(myfile.read())

Output

输出量

  1. 27 bytes written to the file.
  2. file content...
  3. Hello friends, how are you?
  4. file content from 6th position...friends, how are you?
  5. file content from 0th position...
  6. Hello friends, how are you?
  7. file content from 12th position...
  8. s, how are you?

翻译自: https://www.includehelp.com/python/file-seek-method-with-example.aspx

python 示例

发表评论

表情:
评论列表 (有 0 条评论,197人围观)

还没有评论,来说两句吧...

相关阅读