1 # 写方法1 2 f = open('tmp.txt','w') 3 f.write('hello world') 4 f.close() 5 6 # 写方法2 7 with open('tmp.txt','w') as f: 8 f.write('hello \n word') 9 10 # 读 11 with open('tmp.txt', 'r') as f: 12 print(f.read()) 13 14 # 逐行读 15 with open('tmp.txt','r') as f: 16 for line in f.readlines(): 17 print(line.strip())#strip()去除空行
怕什么真理无穷,进一寸有一寸的欢喜。---胡适