通過指明打開的檔案和模式來建立一個file類的執行個體。模式可以為讀模式('r')、寫模式('w')或追加模式('a')。
用寫模式打開檔案,然後使用file類的write方法來寫檔案,最後用close關閉這個檔案。再一次打開同一個檔案來讀檔案。如果程式中沒有指定模式,讀模式會作為預設的模式。在一個循環中,使用readline方法讀檔案的每一行。這個方法傳回包括行末換行符的一個完整行。是以,當一個 空的 字元串被傳回的時候,即表示檔案末已經到達了,于是我們停止循環。
注意,因為從檔案讀到的内容已經以換行符結尾,在print語句上使用逗号來消除自動換行。
下面的例子使用了 file, open兩種方式來讀取檔案,注意兩者的不同。
#!/etc/bin/python
#!-*- coding:utf8 -*-
# filename using_file.py
content ='''\
this is a test file,using file class to make a new file with this text
yangql is a boy ,like oracle ,although there is lots of things there for me to
learn .i think it is a good chance to be a excellent dba '''
filename= 'yangql-dba.txt'
fileobj = file(filename,'w')--以寫的方式建立一個檔案
fileobj.write(content)--向檔案中寫入内容
fileobj.close()
f = file(filename) --以file()的方式打開剛才建立的檔案,預設是讀。
print '-----------------make file yangql-dba.txt successfully!!--------------'
print '-----------------the follow text comes from yangql-dba.txt-------------'
print ' '
while true:
line = f.readline()
if len(line) ==0:
break
print line,
f.close()
print '----------------the follow text comes from open class func------------'
fobj = open(filename,'r')
for eachline in fobj:
print eachline,
fobj.close()
"using_file.py" 36l, 853c written
[yang@rac1 python]$ python using_file.py
-----------------make file yangql-dba.txt successfully!!--------------
-----------------the follow text comes from yangql-dba.txt-------------
learn .i think it is a good chance to be a excellent dba
----------------the follow text comes from open class func------------
learn .i think it is a good chance to be a excellent dba
[yang@rac1 python]$