读文件内容
fp = open(r’F:\1.txt’,‘r’) # 后面的r表示read读取, fp 文件句柄
a = fp.read()
print(a)
fp.close() #文件读取完毕之后,一定要关闭文件,否则会占用资源
或者第二种方法使用with语句自动关闭句柄
with open(’/var/log/yum.log’,‘r’,encoding=‘utf-8’) as f:
content = f.read()
print(a)
给文件写内容
追加写入(注意如果想重新起一行写的话换行符要自己添加,不然会在原本内容的最后一行结尾写进去)
with open(‘D:\test.txt’,‘a’,encoding=‘utf-8’) as f:
text = ‘\n奔涌吧,后浪’
f.write(text)
替换写入
with open(‘D:\test.txt’,‘w’,encoding=‘utf-8’) as f:
text = ‘运用之妙,存乎一心’
f.write(text)