文件最重要的功能是提供和接收数据, 在二进制模式下,基本上分别将str和bytes类用作数据。文件读写之前,首先打开文件,打开文件的模式有如下几种模式:
1.使用f.read()f方式读取文件
>>> f=open(''somefie.txt','r')
>>> f.read()
>>> f.close() ##关闭文件
或者:
>>> with open(''somefie.txt','r) as f:
>>> a= f.read()
2.使用 f.readline()按行读取文件
>>> with open(''somefie.txt','r') as f:
>>> while True:
>>>line=f.readline()
>>>if not line: #读取空行退出循环
>>> break
3.使用f.readlines() 将文件按行一次性读取到一个字符列表中
>>> with open(''somefie.txt','r') as f:
>>>a= f.readlines()
1.使用f.write()写入文件
>>> with open(''somefie.txt','w') as f:
>>> f.write(''helloworld')
2.使用f.writeline()写入文件(请注意:写入时不会添加换行符,需要自行添加)
txtlist =['maths\n','chinese\n','english\n']
>>> with open(''somefie.txt','w') as f:
>>> f.writelines(txtlist)
tell()函数返回指针在文件中的位置;
seek(offset[,whence]) 函数,是将当前位置的(执行读写的位置)移到offset和whence指定地方;offset可正可负,正数表示向后面移动到offset位,负数表示向前面移动到offset位; whence有0,1,2三个参数,0表示指针移动到文件开头,1表示指针在当前位置,2表示指针移动到文件结尾。
with open('char','r') as f:
#print(f.read())
f.seek(0,0) 表示移动到文件的开头
#print(f.read())
f.seek(3,0)
print(f.tell()) #输出为3
联系客服