文件的操作方法
文件只读:r rb
1 f = open('文件位置', mode='r', encoding='utf-8') # 文件位置可以为绝对为位置,在根目录下开始的位置,在与程序在相同目录下的为相对位置
2 # mode 填写读写方式 r:文件只读 rb:f = open('文件位置', mode='rb') 不需写encoding,默认编码方式是bytes类型
3 # rb用在非文字文件上传与下载用
4 content = f.read()
5 print(content)
6 f.close()
可以定义读的多少 以字符为单位
1 f = open('sos', mode='r', encoding='utf-8')
2 content = f.read(2) # 读出来的都是字符
3 print(content)
4 f.close()
文件只写 :w wb 没有此文件就创建此文件,有就覆盖 步骤:把原文件的内容全部清除再写
1 # 对于w:没有此文件就会创建文件,有就覆盖 步骤:把原文件的内容全部清除再写
2 # f = open('sos', mode='w', encoding='utf-8')
3 # f.write('3838438') # .write:所需写入的内容
4 # f.close()
5 f = open('sos', mode='wb')
6 f.write('6666666'.encode('utf-8')) # 默认编码方式用.encode定义编码方式
7 f.close()
文件追加: a ab 模式 ab为bytes编码方式
1 f = open('sos', mode='a', encoding='utf-8')
2 f.write('88888')
3 f.close()
4 f = open('sos', mode='ab')
5 f.write('999'.encode('utf-8'))
6 f.close()
读写 r+ r+b(以bytes类型)先把原文章读出来 再写进去 打印后写进的文字
1 f = open('sos', mode='r+', encoding='utf-8')
2 print(f.read())
3 f.write('中国')
4 f.close()
5 f = open('sos', mode='r+b') # bytes类型 读也会显示为bytes类型 注意汉子
6 print(f.read())
7 f.write('38'.encode('utf-8'))
8 f.close()
w+ 写读 先清除所有文字再重新写 如果不加seek 则不会读出东西
1 f = open('sos', mode='w+', encoding='utf-8')
2 f.write('ss,dd')
3 f.seek(0) # 移动光标到句头位置
4 print(f.read())
5 f.close()
seek 操作光标 操作光标是按字节去找 (注意中文1字符=3字节)
1 f = open('sos', mode='r+', encoding='utf-8')
2 counter = f.seek(3) # 是按字节定光标的位置
3 print(counter)
4 print(f.read())
5 f.close()
.tell:告知光标的位置
1 f = open('sos', mode='r+', encoding='utf-8')
2 counter = f.seek(3)
3 print(f.tell()) # 告知光标的位置
4 f.close()
自动关闭close with 可以打开多个文件
1 with open('sos', mode='r', encoding='utf-8') as f,\
2 open('day_5', mode='r', encoding='utf-8') as f1:
3 print(f.read(), f1.read())