写文件
writefile
%%writefile ./data/testFile.txt
hello python
jin tian tian qi bu cuo
open覆盖
txt=open('./data/testFile.txt','w')#w会覆盖原内容 txt.write('jin tian tian qi bu cuo\n') txt.write('hello python\n') txt.close()
open追加
txt=open('./data/testFile.txt','a')#a会追加 txt.write('123\n') txt.write('456\n') txt.close()
写入异常
txt=open('./data/testFile.txt','w') try: for i in range(100): 10/(i-50) txt.write(str(i)+'\n') except Exception: print("error:",i) finally: txt.close()
读文件
读取所有内容
txt=open('./data/testFile.txt') txt_read=txt.read() print(txt_read)
按行读取
txt=open('./data/testFile.txt') lines=txt.readlines() print(lines)
print(type(lines))
for line in lines: print('cur_line:',line)
open读取
txt=open('./data/testFile.txt','w')#w会覆盖原内容 for i in range(5): txt.write(str(i)+'\n') txt.close() txt1=open('./data/testFile.txt','r')#r是读取 print(txt1.read()) txt1.close()
关闭文件
使用open打开后,一定要记得使用close关闭。
写入时打开,如果不关闭,则内容无法写入,内容是在关闭时写入文件的。
txt.close()
打开后自动关闭
with open('./data/testFile.txt','w') as f: try: for i in range(100): 10/(i-50) f.write(str(i)+'\n') except Exception: print("error:",i)