1、# 首先定义路径存为变量path1 = r'D:\desk\1.txt'
2、# path1路径 w:只写打开文件 utf-8:以怎样的编码打开文件 as f:打开后接口存为fwith open(path1, 'w', encoding='utf-8') as f: pass
3、with open(path1, 'w&拭貉强跳#39;, encoding='utf-8') as f: s = 'good.123.lov髫潋啜缅e.456.make' f.write(s) f.flush() # 刷新缓冲区,类似于word中点击保存 f.seek(0) f.write('dog') # 代码执行后,会自动关闭文件。
4、with open(path, 'a', encoding='utf-8') as f: f.write('ying') f.flush() f.seek(0) f.write('love')
5、path = r'D:\desk\4.txt'with open(path, 'wb媪青怍牙') as f: s = 'good morning 水立方' code = s.encode(encoding='utf-8') f.write(code)
6、# 查看4.txtpath = r'D:\desk\4.txt'with open(path, 'r', encoding='utf-8') as f: print(f.read())