• 技术文章 >Python技术 >Python基础教程

    python truncate是什么

    小妮浅浅小妮浅浅2021-03-17 11:15:26原创3603

    1、说明

    从文件的首行首字符开始截断,截断文件为n个字符;无n表示从当前位置起截断;截断之后n后面的所有字符被删除。

    2、语法

    1

    fileObject.truncate( [ size ])

    3、参数

    size,可选,如果存在则文件截断为 size 字节。

    4、返回值

    该方法没有返回值。

    5、实例

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    20

    21

    22

    23

    24

    25

    26

    27

    28

    29

    30

    31

    32

    33

    34

    35

    36

    37

    #!/usr/bin/python

      

    # Open a file

      

    fo = open("foo.txt", "rw+")

      

    print "Name of the file: ", fo.name

      

    # Assuming file has following 5 lines

      

    # This is 1st line

      

    # This is 2nd line

      

    # This is 3rd line

      

    # This is 4th line

      

    # This is 5th line

      

    line = fo.readline()

      

    print "Read Line: %s" % (line)

      

    # Now truncate remaining file.

      

    fo.truncate()

      

    # Try to read file now

      

    line = fo.readline()

      

    print "Read Line: %s" % (line)

      

    # Close opend file

      

    fo.close()

    当我们运行上面的程序,它会产生以下结果:

    1

    2

    3

    4

    5

    Name of the file: foo.txt

      

    Read Line: This is 1st line

      

    Read Line:

    以上就是python truncate方法的介绍,在裁剪文件方面经常会使用到,可以就这种方法先进行一个练习。更多Python学习指路:python基础教程

    (推荐操作系统:windows7系统、Python 3.9.1,DELL G3电脑。)

    专题推荐:python truncate
    上一篇:python idle 是什么 下一篇:python os模块怎么用?

    相关文章推荐

    • python title是什么• python module的使用• python while是什么• python round()函数是什么• python是什么蛇• python gil是什么• python自动化是什么• python idle 是什么

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网