f = open('文件的路径',mode='r',encoding='utf-8') # mode是指以什么方式打开文件,encoding是要打开的文件的编码方式
# 当mode的值为rb的时候,就不需要写encoding编码方式了,rb用于打开非文字类的文件(如图片)或者上传下载文件的时候
content = f.read()
print(content)
f.close()
# 没有文件的话,则创建文件,如果源文件中有内容,则先删除源文件中的内容然后再写入内容
# 方法一
f = open('ceshi',mode='w',encoding='utf-8')
f.write('ceshi')
f.close()
# 方法二
f = open('ceshi',mode='wb')
f.write('ceshi'.encode('utf-8'))
f.close()
f = open('路径',mode='a',encoding='utf-8')
f.write('ceshi')
f.close()
f = open('路径',mode='ab')
f.write('ceshi'.encode('utf-8'))
f.close()
f = open('ceshi',mode='r+',encoding='utf-8')
# 先读后写
print(f.read())
f.write('xiaosheng')
f.close()
# 如果是先写后读的话,因为一开始写的时候光标是在第一个位置,所以写的内容会把原文件中的内容从头开始替换,比如说原文件中有五个字符(abcde),现在要写入三个(fff),那么读出来的结果会是de,而文件中的内容会变成fffde。
# ceshi文件中有abcdef
f = open('ceshi',mode='a+',encoding='utf-8')
# 现在想要继续向ceshi文件中添加def内容
f.write('def')
f.seek(0) # 可以追加重复的内容,seek是寻找光标,seek是按照字节来找的
print(f.read())
f.close()
功能介绍
f = open('ceshi',mode='r+',encoding='utf-8')
#contents = f.read(3)
#print(contents) # abc
f.seek(3) # seek是按照字节来定光标的位置
content = f.read()
print(content) #defghigk
f.close()
- 找到光标的位置
print(f.tell()) --- 打印出光标的位置
- readable() --- 是否可读
- readline() --- 一行一行的读
- readlines() --- 读出来是一个列表
with open('ceshi',mode='r',encoding='utf-8') as f:
print(f.read()) # 此种写法不用关闭文件,自带了关闭文件操作
网友评论