python教程:文件操作

2024-10-24 10:33:40

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教程:文件操作
猜你喜欢