普通人怎么样做网站,有关于网站建设的参考文献,外贸中东哪些产品好卖,好男人 好资源视频概述Python 文件 truncate() 方法用于截断文件并返回截断的字节长度。指定长度的话#xff0c;就从文件的开头开始截断指定长度#xff0c;其余内容删除#xff1b;不指定长度的话#xff0c;就从文件开头开始截断到当前位置#xff0c;其余内容删除。语法truncate() 方法…概述Python 文件 truncate() 方法用于截断文件并返回截断的字节长度。指定长度的话就从文件的开头开始截断指定长度其余内容删除不指定长度的话就从文件开头开始截断到当前位置其余内容删除。语法truncate() 方法语法如下1fileObject.truncate([size])参数size -- 可选如果存在则文件从开头截断为指定字节。返回值该方法没有返回值。实例以下实例演示了 truncate() 方法的使用文件 365jz.txt 的内容如下123451:www.365jz.com2:www.365jz.com3:www.365jz.com4:www.365jz.com5:www.365jz.com循环读取文件的内容1234567891011121314151617#!/usr/bin/python3fo open(365jz.txt, r, encodingutf-8)# print (文件名: , fo.name)fo.seek(36)fo.truncate() # 从第36个字节以后的内容全部删除了fo.seek(0,0)line fo.readlines()print(读取行: %s % (line))fo.truncate(10) # 截取10个字节fo.seek(0,0)str fo.read()print(读取数据: %s % (str))# 关闭文件fo.close()以上实例输出结果为123文件名: 365jz.txt读取行: [1:www.365jz.com\n, 2:www.365jz.com\n]读取数据: 1:www.365j假设’foo.txt‘文件中包含以下行 -This is 1st lineThis is 2nd lineThis is 3rd lineThis is 4th lineThis is 5th lineShell以下示例显示了truncate()方法的用法。#!/usr/bin/python3fo open(foo.txt, r)print (Name of the file: , fo.name)line fo.readline()print (Read Line: %s % (line))posfo.tell()print (current position : ,pos)# Close opened filefo.close()Python执行上面代码后将得到以下结果 -Name of the file: foo.txtRead Line: This is 1sRead Line: []