python教程:文件操作

2025-11-01 12:25:55

1、打开文件

# -*- coding: utf-8 -*-

 

# 创建文件

 

fd = open("1.log","w")

执行上面的代码,你会发现新建了一个空文件。原来不存在文件就会创建文件。

python教程:文件操作

2、我们先读取一个不存在的文件:注意第二个参数我改成r。

fd = open("2.log","r")

这会包一个错误

python教程:文件操作

3、加上异常处理,这在真正商用环境很常见。

try:

 

   fd = open("2.log","r")

 

except Exception as e:

 

   print "Exception(%s)"% str(e);

python教程:文件操作

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")

python教程:文件操作

5、文件的读取:

fd = open("1.log","r")

 

s = fd.read();

 

print s;

python教程:文件操作

6、读取一行的例子:

fd = open("1.log","r")

 

s = fd.readline();

 

print s;

python教程:文件操作

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