文件對象不僅可以用來訪問普通的磁盤文件,也可以訪問其他類型抽象層面上的"文件",下面介紹open函數在python操作文件上的常用方法。
file_object=open(file_name,access_mode='r',buffering='-1')
access_mode:文件使用模式,在open函數中默認為只讀。其他模式還有:
w:以寫方式打開
a:以追加模式打開
r+:以讀寫模式打開
w+:以讀寫模式打卡
rb:以二進制讀模式打開
wb:以二進制寫模式打開
ab:以二進制追加模式打開
rb+:以二進制讀寫模式打開
wb+:以二進制讀寫模式打開
ab+:以二進制追加模式打開
open對象常用的方法
read():讀取字節到字符串中
readline():打開文件的一行,包括行結束符
readline():打開文件,讀取所有行
write():將字符串寫入文件,寫入對象為字符串
writelines():將列表寫入文件,對象是列表。
seek():偏移量
tell():返回當前文件指針的位置
下面是一個例子,創建一個新文件,然后寫入字符串,如果寫入字符為".",則寫入結束,然后打印出文件內容。
#!/usr/bin/env python
import os
filename=raw_input("please input your filename:")
while True:
if os.path.exists(filename):
print "ERROR,the filename exists!"
else:
break
a=[]
while True:
line=raw_input(">")
if line==".":
break
else:
line=line+"\n"
a.append(line)
file=open(filename,"w+")
file.writelines(a)
file.close()
file1=open(filename,"r")
for i in file1:
print i.strip()