python读写文件
来源:互联网 发布:尔雅网络课 编辑:程序博客网 时间:2024/06/01 23:37
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:不能自动换行。
0 0
- python--python读写文件
- Python读写Unicode文件
- python Ini文件读写
- Python读写文件
- Python读写文件
- Python读写ini文件
- Python读写文件
- Python读写文件
- Python文件的读写
- python读写文件
- python文件读写
- [Python]读写文件方法
- python 文件读写操作
- Python文件读写操作
- Python读写文件
- python之读写文件
- python读写文件
- python文件的读写
- 找两个链表的第一个公共结点
- 解决Android SDK Manager更新、下载速度慢
- 递归
- Diff lcs
- 在Eclipse中安装ADT
- python读写文件
- fedora实用一些小软件
- hdu 1240 Asteroids!bfs
- 找出数组中两个只出现一次的数字
- HDOJ 3394 Railway
- 关于thinkphp扩展的继承
- 杭电4770
- Java中的重载与覆盖。
- warning:deprecated conversion from string constant to 'char *'解决方案