python教程:文件操作
1、打开文件
# -*- coding: utf-8 -*-
# 创建文件
fd = open("1.log","w")
执行上面的代码,你会发现新建了一个空文件。原来不存在文件就会创建文件。

2、我们先读取一个不存在的文件:注意第二个参数我改成r。
fd = open("2.log","r")
这会包一个错误

3、加上异常处理,这在真正商用环境很常见。
try:
fd = open("2.log","r")
except Exception as e:
print "Exception(%s)"% str(e);

4、写文件,我们在3.log写入一个test
# -*- coding: utf-8 -*-
# 创建文件
try:
fd = open("3.log","w")
except Exception as e:
print "Exception(%s)"% str(e);
fd.writelines("test")

5、文件的读取:
fd = open("1.log","r")
s = fd.read();
print s;

6、读取一行的例子:
fd = open("1.log","r")
s = fd.readline();
print s;

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
阅读量:143
阅读量:103
阅读量:146
阅读量:85
阅读量:182