Python操作文件和目录 读写文件比较简单,有一点特别注意就好了 windows下Python默认打开的文件以gbk解码,而一般我们的文件是utf-8编码的,所以如果文本含有中文,就会出现异常或者乱码.此时手动添加encoding='utf-8'表示以utf-8的方式打开. 当然Python写入时候,也是默认以gbk的编码写入.而文件通常是utf-8格式保存的,所以若不指定写入的编码方式,一写入中文就是乱码了 with open('abc.txt', encoding='utf-8') as
# python打开文件的N种姿势 print('[1]使用open()函数+简单for循环') f1 = open('python.txt') for line in f1: print(line.strip()) f1.close() print(,'-')) print('[2]使用open()函数打开+逐行读取并打印') f2 = open('python.txt') while True: line = f2.readline().strip() # f1.readline()后面添加