Day8 笔记
文件操作
open 是python的内置函数,open底层调用的是操作系统的接口
f1:就是个变量,专业名词:文件句柄。一般命名f1,fh,file_handler,f_h等等,对文件进行任何操作,都要通过文件句柄。
encoding='' 可以不写,如果不写的话,默认编码本就是操作系统的默认编码
windows:gbk
linux:utf-8
mac:utf-8
mode='' 打开方式,r只读,w写入,a追加……
f1.close() 关闭文件句柄
f1 = open(r'd:\temp\day8test1.txt', encoding='utf-8', mode='r')
content = f1.read()
print(content)
f1.close()
1.文件操作的读
# 1.全部读出来
f1 = open(r'd:\temp\day8test1.txt', 'r', encoding='utf-8', )
context = f1.read()
print(context)
f1.close()
# 2.按照字符读取
f1 = open(r'd:\temp\day8test1.txt', 'r', encoding='utf-8', )
context = f1.read(3)
print(context)
f1.close()
# 3.按照行读取
f1 = open(r'd:\temp\day8test1.txt', 'r', encoding='utf-8', )
context = f1.readline()
print(context)
f1.close()
# 4.多行读取 # 返回一个列表,列表中的每一个元素是源文件中的每一行
f1 = open(r'd:\temp\day8test1.txt', 'r', encoding='utf-8', )
l1 = f1.readlines()
print(l1)
f1.close()
# 5.for循环读取(文件句柄可以遍历)
f1 = open(r'd:\temp\day8test1.txt', 'r', encoding='utf-8', )
for line in f1:
print(line)
# 6.rb 二进制读取,模式操作的是非文本的文件 图片、视频、音频等
f2 = open(r'd:\temp\timg.jfif', 'rb')
pic = f2.read()
print(pic)
f2.close()
2.文件操作的写
# 如果没有这个文件,则创建这个文件
f = open(r'd:\temp\day8test2.txt', 'w', encoding='utf-8')
f.write('现在学习文件的写')
f.close()
# 如果文件存在,就先清空,再写入新内容
f = open(r'd:\temp\day8test2.txt', 'w', encoding='utf-8')
f.write('重新写一点')
f.close()
# 二进制写入
f1 = open(r'd:\temp\timg.jfif', 'rb')
pic = f1.read()
print(pic)
f1.close()
f2 = open(r'd:\temp\美女.jfif', 'wb')
f2.write(pic)
f2.close()
3.文件操作的追加
# 没有文件先创建文件再追加
f = open(r'd:\temp\day8test2.txt', 'a', encoding='utf-8')
f.write("adfslkdjflskdjf")
f.close()
4.文件操作的读写
# r+ 读并追加
f = open(r'd:\temp\day8test2.txt', 'r+', encoding='utf-8')
content = f.read()
print(content)
f.write('我好烦')
5.文件操作的其他功能
# tell() 读取光标所在的位置,单位(字节)
f = open(r'd:\temp\day8test2.txt', 'r', encoding='utf-8')
print(f.tell())
content = f.read()
print(f.tell())
f.close()
# seek() 调整光标的位置
f = open(r'd:\temp\day8test2.txt', 'r', encoding='utf-8')
print(f.tell())
f.seek(9)
print(f.tell())
content = f.read()
print(content)
f.close()
# flush 强制刷新
f = open(r'd:\temp\day8test2.txt', 'w', encoding='utf-8')
f.write('强制保存')
f.flush()
f.close()
6.打开文件的其他方式
# 不用手动关闭文件句柄
# 可以同时打开多个文件
with open(r'd:\temp\day8test1.txt', 'r', encoding='utf-8') as f1,\
open(r'd:\temp\day8test2.txt', 'r+', encoding='utf-8') as f2:
print(f1.read())
print(f2.read())
f2.write('jason')
7.修改文件的操作
"""
1. 以读的方式打开原文件
2. 以写的模式创建一个新文件
3. 将原文件读取出来的内容修改为新内容,写入新文件
4. 将原文件删除
5. 将重命名为新文件
"""
import os
with open(r'D:\temp\day8test3.txt', 'r', encoding='utf-8') as f1,\
open(r'D:\temp\day8test4.txt', 'w', encoding='utf-8') as f2:
for line in f1:
new_line = line.replace('SB', 'NB')
f2.write(new_line)
os.remove(r'D:\temp\day8test3.txt')
os.rename(r'D:\temp\day8test4.txt', r'D:\temp\day8test3.txt')