python读写文件
1.读文件
open使用open打开文件后一定要记得调用文件对象的close()方法。比如可以用try/finally语句来确保最后能关闭文件。
html = “D:\App781286.html”
file = open(html)
try:
text = file.read()
finally:
file.close()
注:不能把open语句放在try块里,因为当打开文件出现异常时,文件对象file_object无法执行close()方法
2.写文件
只写(会覆盖之前的内容)
f = open(‘D:\html.txt’, ‘w’)
f.writelines(hp.links)
f.close()
追加写
f = open(‘D:\download.txt’, ‘a’)
for text, links in items :
f.write(“%s : %s \n” % (text, links))
f.close()
注:
使用 self.links.append(value + ‘\n’)打出来的是数组,如果想要正常写入 f.writelines(hp.links)
.writelines:不能自动换行。
还没有评论,来说两句吧...