python的文件操作
一、文件操作常见的模式
①:r模式
file=open('docx.txt',mode='r',encoding='utf-8') print(file.read()) # 人生苦短,我用Python file.close()
②:w模式
file=open('docx.txt',mode='w',encoding='utf-8') #如果写入的文件不存在,那么会自动创建文件 file.write('人生苦短,我用Python') file.close()
③:rb模式
file=open('docx.txt',mode='rb') print(file.read()) # 人b'\xe4\xba\xba\xe7\x94\x9f\xe8\x8b\xa6\xe7\x9f\xad\xef\xbc\x8c\xe6\x88\x91\xe7\x94\xa8Python' file.close()
④:wb模式
file=open('docx.txt',mode='wb') file.write('人生苦短,我用Python'.encode('utf-8')) file.close()
⑤:r+模式
①:先读后写
file=open('docx.txt',mode='r+',encoding='utf-8') print(file.read()) #人生苦短,我用Python file.write('打发时间') print(file.read()) #写完之后,光标移动至行尾,读到的是空白的文件 file.close()
②:先写后读:
file=open('docx.txt',mode='r+',encoding='utf-8')
file.write('Python')
print(file.read()) #苦短,我用Python Python占六个字节,将会替换 “人生”,然后光标移至python后,读取来 ‘苦短,我用Python’
file.close()
⑥:w+模式 无论是先写后读,还是先读后写,都会进行文件的覆盖
①:先写后读
file=open('docx.txt',mode='w+',encoding='utf-8') file.write('Python') print(file.read()) #Python file.close()
②:先读后写
file=open('docx.txt',mode='w+',encoding='utf-8') print(file.read()) file.write('Python') print(file.read()) file.close()
二、文件操作seek(),tell(),truncate()方法
①:seek()方法
seek(offset,whence=0) 移动文件读取指针到制定位置
offset:开始的偏移量,也就是代表需要移动偏移的字节数。
whence: 给offset参数一个定义,表示要从哪个位置开始偏移;0代表从文件开头算起,1代表开始从当前位置开始算起,2代表从文件末尾开始算起。当有换行时,会被换行截断。
file=open('docx.txt',mode='r',encoding='utf-8') file.seek(3) print(file.read()) #lo Python ''' docx.txt文件内容如下: Hello Python '''
②:truncate(size):truncate用于在文件读取时截取文件,如果不设置参数,那么会默认从光标处截取到文件的末尾
如果设置了参数,会截取指定大小的字符
file=open('docx.txt',mode='r+',encoding='utf-8') file.truncate(12) file.seek(0) print(file.read()) #Hello Python ''' docx.txt文件内容如下: Hello Python Hello Java '''
③:tell():告诉读取文件时光标所在的位置
file=open('docx.txt',mode='r',encoding='utf-8') file.seek(3) print(file.tell())