小白教程
所有教程
关于
Search
172.71.254.219
172.71.254.219
参数设置
贡献
退出
操作
编辑
移动
保护
信息
历史
删除
查看“Python3 file truncate”的源代码
本页内容
上一节:
Python3_file_tell
下一节:
Python3_file_write
因为以下原因,您没有权限编辑本页:
您请求的操作仅限属于该用户组的用户执行:
用户
您可以查看和复制此页面的源代码。
{{DISPLAYTITLE:file.truncate([size])}}[[Category:python3 file methods|11]] = Python3 File truncate() 方法 = [[python3 file methods|Python3 File(文件) 方法]] === 概述 === '''truncate()''' 方法用于从文件的首行首字节开始截断,截断文件为 size 个字节,无 size 表示从当前位置截断;截断之后 V 后面的所有字节被删除,其中 Widnows 系统下的换行代表2个字节大小。 。 === 语法 === truncate() 方法语法如下: <sample title="" desc="" lang="python" hererun="1"> fileObject.truncate( [ size ]) </sample> === 参数 === * '''size''' -- 可选,如果存在则文件截断为 size 字节。 === 返回值 === 该方法没有返回值。 == 以下实例演示了 truncate() 方法的使用: 文件 xiaobai.txt 的内容如下: <sample title="" desc="" lang="python" hererun="1"> 1:www.xiaobai.wang 2:www.xiaobai.wang 3:www.xiaobai.wang 4:www.xiaobai.wang 5:www.xiaobai.wang </sample> 循环读取文件的内容: <sample title="" desc="" lang="python" hererun="1"> #!/usr/bin/python3 fo = open("xiaobai.txt", "r+") print ("文件名: ", fo.name) line = fo.readline() print ("读取行: %s" % (line)) fo.truncate() line = fo.readlines() print ("读取行: %s" % (line)) # 关闭文件 fo.close() </sample> 以上实例输出结果为: <sample title="" desc="" lang="python" hererun="1"> 文件名: xiaobai.txt 读取行: 1:www.xiaobai.wang 读取行: ['2:www.xiaobai.wang\n', '3:www.xiaobai.wang\n', '4:www.xiaobai.wang\n', '5:www.xiaobai.wang\n'] </sample> 以下实例截取 xiaobai.txt 文件的10个字节: <sample title="" desc="" lang="python" hererun="1"> #!/usr/bin/python3 # 打开文件 fo = open("xiaobai.txt", "r+") print ("文件名为: ", fo.name) # 截取10个字节 fo.truncate(10) str = fo.read() print ("读取数据: %s" % (str)) # 关闭文件 fo.close() </sample> 以上实例输出结果为: <sample title="" desc="" lang="python" hererun="1"> 文件名为: xiaobai.txt 读取数据: 1:www.runo </sample> [[python3 file methods|Python3 File(文件) 方法]]
返回至“
Python3 file truncate
”。
上一节:
Python3_file_tell
下一节:
Python3_file_write