open函数返回的是一个文件对象,时可迭代的
f=open(file path,mode=“r”)
(更推荐,因为会自动关闭文件)with open(file path,mode=“r”) as f:
r 读取文件
w 清除掉原来的重新写入
a 在最后一句之后追加
r+=r+w 读取并在制定文段后添加 (在文本文件test.txt的中间部分添加一行字符串)
w+=w+r
a+=a+r
f.read(size)从文件中读出至多前size字节数据,返回一个字符串
f.read() 从当前光标读至文件结束,返回一个字符串
f.readline()
f.readlines() 返回多行数据,一个列表(不会自动删除换行符 )
f.write() 将一个字符串写入文件
f.writelines()
把文件companies.txt的字符串前面加上序号1,2,3...然后写入到另一个文件scompanies.txt中
with open( "comapnies.txt") as f1:
cNames=f1.readlines()
for i in range(1, len(cNames)+1):
cNames[i]=str(i)+" "+cNames[i]
with open("scomapnies.txt",mode="w")as f2:
f2.writelines(cNames)
f.seek(offset,whence=0):offset偏移量,whence起始位置,默认为0
0表示文件头部,1表示当前位置,2表示文件尾部
例如:f.seek(0)表示把文件指针移动到文件开头
f.seek(50,1) 表示把文件指针从当前位置向后移动50个字节
with open( "comapnies.txt","a+") as f1:
f.write("\n")
f.writelines(s) #此时指针就在最后面了
f.seek(0)
cNames=f.readlines()
cNames
f.close()
try:
with open( "comapnies.txt") as f1:
data=f1.readlines()
except FileNotFoundError:
print( "comapnies.txt"+"not found")
lens=len(data) #计算txt文件的行数