python文件操作.txt
1、找到文件路径,绝对路径:d:\文件.txt 和相对路径
2、知道文件储存的编码方式:utf-8,gbk等,encoding要对应上文件的编码方式,否则会报错或者乱码
3、操作方式:只读,只写,读写,写读,追加。。。
4、操作完成,关闭文件,否则会一直占用内存
f = open(‘f:\python文件操作.txt‘,mode=‘r‘,encoding=‘utf-8‘) #这相当于一个文件句柄 content = f.read() print(content) f.close()
f = open(‘python3‘,mode=‘r‘,encoding=‘utf-8‘) #这是打开在同一路径下的文件 content = f.read() print(content) f.close()
f = open(‘python3‘,mode=‘rb‘) content = f.read() print(content) f.close()
f = open(‘log‘,mode=‘w‘,encoding=‘utf-8‘) f.write(‘hahaha‘) f.close()
f = open(‘log‘,mode=‘wb‘) f.write(‘he审核的和hehe‘.encode(‘utf-8‘)) f.close()
f = open(‘log‘,mode=‘a‘,encoding=‘utf-8‘) f.write(‘我要杀光蚊子‘) f.close()
f = open(‘log‘,mode=‘ab‘) f.write(‘我要hhhhhhh‘.encode(‘utf-8‘)) f.close()
原文:https://www.cnblogs.com/seven-wenzi/p/14608736.html