使用open打开文件后一定要记得调用文件对象的close()方法。比如可以用try/finally语句来确保最后能关闭文件。
file_object = open('thefile.txt')
try:
all_the_text = file_object.read( )
finally:
file_object.close( )
try:
all_the_text = file_object.read( )
finally:
file_object.close( )
注:不能把open语句放在try块里,因为当打开文件出现异常时,文件对象file_object无法执行close()方法。
<span style="color:#000000;"> #coding:utf-8
#!/usr/bin/python
# Filename: fileRW.py
import os
context=""" hello world,hello
"r" 以读方式打开,只能读文件 , 如果文件不存在,会发生异常
"w" 以写方式打开,只能写文件, 如果文件不存在,创建该文件
如果文件已存在,先清空,再打开文件"""
def createfileBYwrite(filename):
f = open(filename,'w') #打开文件open()是file()的别名
f.write(context) #把字符串写入文件
f.close() #关闭文件
#注意,调用writelines写入多行在性能上会比使用write一次性写入要高。
def createfileBYwritelines(filename):
f = open(filename,'w') #打开文件open()是file()的别名
try:
f.writelines(context) #把字符串写入文件
finally:
f.close() #关闭文件
def readBYreadline(filename):
f = open(filename)
while True:
line =f.readline()#当文件指针移动到末尾继续readline会出现错误,所以后面要加判断
if line:
print line,
else:
break
f.close()
#需要通过循环访问readlines()返回列表中的元素
def readBYreadlines(filename):
f = open(filename)
try:
lines = f.readlines()
for line in lines:
print line,
finally:
f.close()
#从文件中读取所有内容,赋予一个字符串变量
def readBYread(filename):
f = open(filename)
try:
content = f.read()
finally:
f.close()
print content
if __name__== "__main__":
filename="hello.txt"
createfileBYwritelines(filename)
readBYread(filename)
#把文件删除掉
if os.path.exists(filename):
print "文件存在%s" %filename
os.remove(filename)
hello world,hello
"r" 以读方式打开,只能读文件 , 如果文件不存在,会发生异常
"w" 以写方式打开,只能写文件, 如果文件不存在,创建该文件
如果文件已存在,先清空,再打开文件
文件存在hello.txt
</span>