根据编码方式Python将文件分为:文本文件和二进制文件。 用内置函数open()读写文件 一、原始写法 f = open('xxx1.py','w+',) //读写,覆盖,创建;二进制wb+;追加用a+ f.write('1 hello world \n') //f.read() //一次性读取文件的所有内容 //f.seek(0) //读取文件后文件指针移到最前 f.close() 备注:可以用uos.remove('xxx1.py')删除文件,uos.remove('lezi')删除文件夹 1.写入变量 strFile = 'hello TXT' f = open('111.py','w+') f.write(strFile) f.close() 2.读取文件内容 f = open('111.py','r') f.read() f.close() 3.批量代码操作方法: 3.1 Ctrl+E //代码粘贴模式,或者书写多行代码 3.2 鼠标右键 //粘贴代码 3.3 Ctrl+D //运行代码 二、用with open语句写入文件或读取文件内容 #写入文件 with open('xxx.py','w') as f: f.write(strFile) #查看文件内容 with open('xxx.py','r') as f: print(f.read())