1、知识点补充
2、编码
3、集合
4、深浅copy
5、文件操作
file1
= open("D:/myclass/课堂文件/day02/day02/02 字符串.py",encoding='utf-8',mode='r')
print(file1.read())
encoding类型多为utf-8或gbk,如果不正常会字符集报错
由于在windows中路径会识别特殊字符,比如换行符,可以在文件路径前加r来转义,如: r"D:/myclass/课堂文件/day02/day02/02 字符串.py"
在mode中 r为只读,r下的read(n)中的n是按照字符个数读取
rb用来操作bytes模式,非字符文件,如图片,视频 rb模式下read(n)中的n是按照字节读取 r+ : 先读后写功能
readline() 读取一行
readlines() 读取全部放入一个列表中,将每一行做为一个列表的元素。
for循环读取文件句柄: for line in file1: print(line)
文件写模式:w, wb file1 = open(r"D:\myclass\123\test.txt",mode='w') file1.write('aaa\nccc') file1.flush() 写模式会清空文件,如果文件不存在,会创建此文件
w+: 先写后读功能
追加模式: a , ab file1 = open(r"D:\myclass\123\test.txt",mode='a') file1.write('yyyy\nqqqq') file1.flush() 不会清空原文件内容,在后面追加内容
a+: 先追加再读取功能
文件其他操作: read, readline, readlines, write
close, flush, readable(判断文件是否可读) writable(是否可写) seek()调整指针到指定位置 seek(0,2) : 将指针调到最后的位置 tell() 显示光标的位置 truncate():按照字节对原文件截取指定的数据,必须在a或a+模式
自动关闭文件句柄: with open(r"D:\myclass\123\test.txt",encoding='utf-8',mode='r') as file1: print(file1.read())
可以一次操作多个文件句柄: with open(r"D:\myclass\123\test.txt",encoding='utf-8',mode='r') as file1, \ open(r"D:\myclass\123\test2.txt", mode='w') as f2: content = file1.read() f2.write(content)
文件的改: 1、以读模式打开原文件 2、以写模式打开新文件 3、将原文件内容读出修改后得到的内容再写入到新文件 4、删除原文件 5、保存新文件为原文件名
函数 函数的执行:函数名加括号 函数的返回值: return 函数的参数: 形参,实参。