在python中,文件其實就是對象。通過open()函數,打開文件,文件的屬性包括讀文件,寫文件,關閉文件等.
1.python文件打開方式
1.1文件打開方法
open(name[,access_mode='r'[,buffering=-1]])
name:文件路徑
access_mode:打開方式,可選選項,默認以只讀的方式打開。下方會詳細介紹幾種模式的區別。
buffering:用於指示訪問文件所采用的緩沖方式,可選選項,默認是使用系統默認緩沖機制。其中0表示不緩沖。1表示只緩沖一行數據,任何大於1的值代表使用給定值作為緩沖區大小。不提供該參數或者給定負值代表使用系統默認緩沖機制。
1.2關於access_mode幾種方式
'r':只讀方式打開。文件必須存在;不支持寫,當文件寫入數據時會報錯。
'w':只寫方式打開。文件不存在創建文件;文件存在則清空文件內容,采用write可重新寫入數據。不支持讀,當讀文件數據時會報錯。
'a':追加方式打開。文件不存在創建文件;文件存在則保留文件內容,采用write可在文件末行追加寫入數據。不支持讀,當讀文件數據時會報錯。
'r+':讀寫方式打開。文件必須存在;保留文件內容,支持寫,采用write可在文件首行處寫入數據,並覆蓋相對應位置的原數據。
'w+':讀寫方式打開。文件不存在創建文件;文件存在則清空文件內容,采用write可重新寫入數據。支持讀。
'a+':以追加方式及讀寫方式打開。文件不存在創建文件;文件存在則保留文件內容,采用write可在文件末行追加寫入數據。支持讀。
'rb','wb','ab','rb+','wb+','ab+':以二進制方式打開文件,其他的和上面一樣。
說明:
1.支持讀,表示可以使用文件屬性read,readline,readlines
2.支持寫,表示可以使用文件屬性write,writelines
3.'w'方式的寫,是清空文件所有內容,重新寫入數據。
4.'a'方式的寫,不清空文件內容,在文件末尾追加的寫入數據。
5.'r+'方式的寫,不清空文件內容,在文件首行處寫入數據,並覆蓋相對應位置的原數據。
舉例:
比如說原文件內容為:
abc
efg
當寫入數據write('xz')
如果以'w'方式打開文件並寫入數據,則文件內容變為:
xz
如果以'a'方式打開文件並寫入數據,則文件內容變為:
abc
efg
xz
如果以'r+'方式打開文件並寫入數據,則文件內容變為:
xzc
efg
關於'r':
>>> import os
>>> os.getcwd() #查看python解釋器當前路徑
'/home/autotest'
>>> os.listdir('/home/autotest') #查看python解釋器當前路徑下有哪些文件,目前只存在hello.py文件
['hello.py']
#文件必須存在,不存在會報錯。
>>> f=open('hello1.py','r+')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IOError: [Errno 2] No such file or directory: 'hello1.py'
#文件支持只讀read();不支持寫write(),寫時報錯。
>>> f=open('hello.py')
>>> f.read()
"#!/usr/bin/env python\nprint 'hello world'\n"
>>> f.write('test')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IOError: File not open for writing
關於'w':
>>> import os
>>> os.getcwd() #查看python解釋器當前路徑
'/home/autotest'
>>> os.listdir('/home/autotest') #查看python解釋器當前路徑下有哪些文件,目前只存在hello.py文件
['hello.py']
#當文件不存在,可創建文件。
>>> fw=open('hello1.py','w')
>>> os.listdir('/home/autotest')
['hello.py', 'hello1.py']
#文件支持只寫write();不支持讀read(),讀時報錯。
>>> fw.write('print w')
>>> fw.read()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IOError: File not open for reading
其他幾種方式就暫不舉例了,大家可以自行地在python解釋器上試試看,多動手就會明白了。
2.文件的屬性
2.1查看文件屬性
>>> f=open("hello.py") #默認以只讀的方式打開
>>> dir(f) #查看文件屬性
['__class__', '__delattr__', '__doc__', '__enter__', '__exit__', '__format__', '__getattribute__', '__hash__', '__init__', '__iter__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'close', 'closed', 'encoding', 'errors', 'fileno', 'flush', 'isatty', 'mode', 'name', 'newlines', 'next', 'read', 'readinto', 'readline', 'readlines', 'seek', 'softspace', 'tell', 'truncate', 'write', 'writelines', 'xreadlines']
2.2文件讀取屬性
read([size]):讀取文件,讀取size個字節。默認讀取全部。
readline([size]):讀取一行,讀取一行中的size個字節。默認讀取一行。
例,如果一行中有10個字節,如果size小於10,則readline(2)則讀取前兩字節,再readline(2)則讀取剩余字節的前兩個字節,再readline()則讀取剩余的六個字節。如果size大於等於10,則讀取一整行。
readlines([size]):讀取完文件(最多是緩沖區DEFAULT_BUFFER_SIZE的字節數),返回每一行所組成的列表(由字符串組成的列表)。
這個size指的是緩沖器的大小,如果給的值為1或者其他數值,文件最多返回8192個字節。
>>> import io
>>> print io.DEFAULT_BUFFER_SIZE
8192
2.3文件寫屬性
write(str):將字符串寫入文件
writelines(sequence_of_strings):寫多行到文件:sequence_of_strings由字符串組成的序列(元組或列表)。
說明:
1.寫文件過程,在python解釋器寫入數據時,先寫到緩沖區,如果不使用close()或者flush(),是不會寫入磁盤,文件修改是不生效的。主動調用close()或者flush(),寫緩存同步到磁盤。如果寫入數據了大於或者等於寫緩存,寫緩存同步到磁盤。
>>> f=open('hello1.py','w+')
>>> f.write('hello1')
>>> f.flush()
>>> f.tell()
6
>>> f.seek(0,os.SEEK_SET)
>>> f.tell()
0
>>> f.read()
'hello1'
>>> f.close()
2.寫入文件后,必須打開才能讀取寫入的內容。
3.讀取文件后,無法重新再次讀取已經讀取過的內容。原因是,文件指針已指向末尾,如果想重新讀取內容,需要將文件指針指向開頭。
>>> f=open('hello1.py','a+')
>>> f.tell()
0
>>> f.read() #第一次讀取可讀取文本內容。
'hello1'
>>> f.tell()
6
>>> f.read() #再次讀取則無法重新獲取內容。原因是,文件指針已指向末尾。
''
>>> f.seek(0,os.SEEK_SET) #文件指針指向開頭,則可以重新讀取內容。
>>> f.tell()
0
>>> f.read()
'hello1'
>>> f.close()
2.4關閉文件屬性
close():要養成良好習慣,使用open打開文件后,讀取文件之后,當不再使用該文件,記得一定要關閉文件哦。因為close()后,數據才會真正的將寫緩存同步到磁盤,才會修改文件成功。並且,如果打開文件數到了系統限制,再打開文件就會失敗。
2.5其他屬性
flush():直接把內部緩沖區中的數據立刻寫入文件。
tell():返回當前文件指針位置
seek(偏移量[,相對位置]):移動文件指針位置,偏移量可正可負。相對位置可以導入os模塊:os.SEEK_SET:相對文件起始位置;os.SEEK_CUR:相對文件當前位置;os.SEEK_END相對文件結尾位置。
fileno():文件描述符
mode:文件打開權限
encoding:文件編碼格式
closed:文件是否關閉。值為False,表示文件未關閉。
3.使用os模塊處理文件
3.1使用OS模塊打開文件
os.open(filename,flag[,mode]):打開文件,返回文件描述符
flag:打開文件方式
os.O_CREAT:創建文件
os.O_RDONLY:只讀方式打開
os.O_WRONLY:只寫方式打開
os.O_RDWR:讀寫方式打開
3.2使用os模塊對文件進行操作
os.read(fd,buffersize):讀取文件,fd為文件描述符
os.write(fd,string):寫入文件
os.lseek(fd,pos,how):文件指針操作,pos是偏移量,how是相對位置:os.SEEK_SET:相對文件起始位置;os.SEEK_CUR:相對文件當前位置;os.SEEK_END相對文件結尾位置。
os.close(fd):關閉文件
3.3os模塊方法介紹
os.access(path,mode):判斷該文件權限:mode:os.F_OK:文件是否存在,os.R_OK:是否有讀權限,os.W_OK是否有寫權限,os.X_OK是否有可執行權限。
os.listdir(path):返回當前目錄下所有文件
os.remove(path):刪除文件
os.rename(old,new):修改文件或者目錄名
os.mkdir(path [,mode]):創建目錄
os.makedirs(path [,mode]):創建多級目錄
os.removedirs(path):刪除多級目錄
os.rmdir(path):刪除目錄(目錄必須為空)
3.4os.path模塊方法介紹
os.path.exists(path):當前路徑是否存在
os.path.isdir(s):是否是一個目錄
os.path.isfile(path):是否是一個文件
os.path.getsize(filename):返回文件大小
os.path.dirname(p):返回路徑的目錄
os.path.basename(p):返回路徑的文件名
os.path.getmtime(path):文件或文件夾的最后修改時間
os.path.join(path1,path2,...):將path進行組合,若其中有絕對路徑,則之前的path將被刪除
舉例說明:
>>> import os
>>> os.getcwd()
'/home/autotest'
>>> os.listdir('/home/autotest')
['hello.py', 'hello1.py', 'hello3.py', 'hello2.py', 'email126pro']
>>> os.path.exists('/home/autotest/hello.py')
True
>>> os.path.exists('hello.py')
True
>>> os.path.exists('/home/autotest/')
True
>>> os.path.isfile('/home/autotest/hello.py')
True
>>> os.path.isfile('hello.py')
True
>>> os.path.isdir('/home/autotest/')
True
>>> os.path.getsize('/home/autotest/hello.py')
42
>>> os.path.getsize('hello.py')
42
>>> os.path.getsize('hello11.py')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib64/python2.6/genericpath.py", line 49, in getsize
return os.stat(filename).st_size
OSError: [Errno 2] No such file or directory: 'hello11.py'
>>> os.path.dirname('hello.py')
''
>>> os.path.dirname('/home/autotest/hello.py')
'/home/autotest'
>>> os.path.dirname('/home/autotest/')
'/home/autotest'
>>> os.path.dirname('/home/autotest')
'/home'
>>> os.path.basename('hello.py')
'hello.py'
>>> os.path.basename('/home/autotest/hello.py')
'hello.py'
>>> os.path.basename('/home/autotest/')
''
>>> os.path.getmtime('/home/autotest/hello.py')
1479450484.9321721
>>> os.path.join('/home/autotest','hello.py')
'/home/autotest/hello.py'