close() 關閉文件對象
flush() 刷新文件的緩沖區。緩沖區包含等待寫入或文件中讀取的信息。“刷新“就是執行實際的讀取或寫入操作
isatty() 如果文件對象是tty(終端)設備,就返回1
read([size]) 從文件中讀取數據。
readline([size]) 從文件中讀取壹行
readlines([size]) 從文件中讀取多行
seek(offset[,location]) 使文件位置移動offset個字節。如果沒有指定location,文件位置從文件起始處移動。如是指定了location,就從指定位置移動。
tell() 返回文件的當前位置
truncate([size]) 刪除文件中的數據。如果沒有指定size,就刪除所有數據;如果指定了size,就最多只刪除指定的字節數。
write(output) 將字符串output寫入文件
writeline(outputlist) 將outputlist中的每個字符串寫入文件
writelines() 寫入多行數據
壹.創建順序訪問文件
寫入文件
import sys
try:
file=open("client.dat","w")
except IOError,message:
print >> sys.stderr, "File could not be opened",message
sys.exit(1)
print "Enter the accout,name and age."
while 1:
try:
accountline=raw_input("?")
except EOFError:
break
else:
print >>file,accountline
file.close()
讀取數據
import sys
try:
file=open("client.dat","r")
except IOError:
print >> sys.stderr, "File could not be opened"
sys.exit(1)
records=file.readlines()
print "Account",ljust(10)
print "Name",ljust(10)
print "age",ljust(10)
for record in records:
fields=record.split()
print fields[0].ljust(10),
print fields[1].ljust(10),
print fields[2].ljust(10),
file.close()
shelve模塊應用
模擬隨機訪問文件:
import sys
import shelve
try:
coutcredit=shelve.open("credit.dat")
except IOError:
print >> sys.stderr,"File could not be opened"
sys.exit(1)
print "Enter account number (1 to 100,0 to end input)"
while 1:
accountNumber=int(raw_input("\nEnter account number\n?"))
if 0 < accountNumber <= 100:
print "Enter lastname, Firetname,balance"
currentData=raw_input("?")
outCredit[str{accountNumber)]=currentDdata.split()
elif accountNumber==0:
break
outCredit.close()
cPickle模塊應用
註:cPickle模塊的執行效率高於pickle
寫文件
import sys
import cPickle
try:
coutcredit=open("credit.dat","w")
except IOError:
print >> sys.stderr,"File could not be opened"
sys.exit(1)
print "Enter account number (1 to 100,0 to end input)"
inputlist=[]
while 1:
try:
accountline=raw_input("?")
except EOFErrot:
break
else:
inputlist.append(accountline.split())
cPickle.dump(inputlist,outCredit)
outCredit.close()
讀出數據
import sys
import cPickle
try:
outcredit=open("credit.dat","r")
except IOError:
print >> sys.stderr,"File could not be opened"
sys.exit(1)
records=cPickle.load(outcredit)
outcredit.close()
for record in records:
print record[0].ljust(15),
print record[1].ljust(10),
print record[2].ljust(20)