1. 程式人生 > >Python內建函式open()詳解&檔案屬性方法詳解

Python內建函式open()詳解&檔案屬性方法詳解

Python檔案物件開啟模式及其屬性方法詳解

1、檔案系統和檔案

檔案系統:檔案系統是OS用於明確磁碟或分割槽上的檔案的方法和資料結構,即在磁碟上組織檔案的方法

檔案:儲存在某種長期儲存裝置或臨時儲存裝置中的一段資料流,並且受計算機檔案系統管理。

概括來講,檔案是計算機中有OS管理的具有名字的儲存區域,在Linux系統上,檔名被看做是位元組序列

檔案<---010100010101010101101-->程序  

2、Python開啟檔案

Python內建函式open()用於開啟檔案或建立檔案物件

open(file_name[mode,[bufsize]])

         file_name:檔名

var_name =open(file_name[mode,[bufsize]])

         mode:指定檔案的開啟模式

                   r:只讀open('/var/log/access.log','r')                   

                   w:寫入

                   a:附加

         在模式後使用“+”表示同時支援輸入、輸出操作,如:

                   r+:讀寫模式,預設以讀模式開啟,不會自動建立檔案

                   w+:寫讀模式,預設以寫模式開啟,會自動建立檔案

                   a+:附加模式

         在模式後附加“b”表示以二進位制方式開啟檔案,如:rb、wb、ab、rb+、wb+、ab+

                   bufsize:輸出緩衝

                   0: 禁用

                   負數:使用系統預設緩衝

                   1:使用緩衝,只緩衝一行資料

                   2+:指定緩衝空間大小

3、檔案物件屬性和方法

f1.close():關閉檔案

f1.flush():清除輸出緩衝區      

f1.next():返回下一行或引發stopTteration,在Python3中,對應方法為f.__next__()

f1.seek(offset[whence]):查詢新檔案位置,whence:起點,0: 從檔案頭,1:從當前位置,2:從檔案尾部

file.seek(offset[whence])

         whence:起點

                   0:從檔案頭

                   1:從當前位置

                   2:從檔案尾部

         offset:偏移量

f1.writelines(line):寫入序列line中的所有字串

f1.read(n):最多讀取n個位元組

f1.softspace:布林值,指示在使用print語句時,是否應該在一個值之前列印空格字元。

f1.xreadlines:讀取檔案,向下相容

f1.encoding:檔案編碼。如果沒有使用任何編碼該值為none

f1.closed:布林值,表示狀態,已開啟則False,已關閉則為True

f1.mode:檔案的   I/O模式

f1.readinto()   

f1.tell():返回當前檔案指標       

f1.errors

f1.name:如果使用open()建立檔案,則為檔名稱,否則,它將是一個表示檔案來源的字串       

f1.readline([n]):讀取單行輸入的最多n個字元,如果省略n,則讀取整行

f1.truncate([n]):將檔案截斷為最多n個字元    

f1.fileno():返回一個整數檔案描述符,從3開始

f1.newlines:在通用換行符模式下開啟一個檔案,該屬性包含可在檔案中實際找到的換行符吧表示。

         如果沒有找到換行符,該值為none,將會看到一個包含'\n','\r'或'\r\n'的字串,或者一個包含所有不同換行符的元組

f1.readlines([size]):讀取所有行並返回一個列表,size用於指定在讀取操作停止前在檔案上讀取的近似字元數  

f1.write(s):寫入字串  

f1.isatty():是否是終端裝置檔案

4、Python檔案操作示例

例1:只讀模式開啟/etc/passwd               

In [1]: f1 = open('/etc/passwd','r')    #只讀模式開啟

In [2]: type(f1)

Out[2]: file     #檔案型別:file

In [3]: f1.      #使用.訪問內建方法  

f1.close       f1.flush       f1.next        f1.seek        f1.writelines

f1.closed      f1.isatty      f1.read        f1.softspace   f1.xreadlines

f1.encoding    f1.mode        f1.readinto    f1.tell       

f1.errors      f1.name        f1.readline    f1.truncate   

f1.fileno      f1.newlines    f1.readlines   f1.write      

In [3]: f1.next()   #使用成員函式next()返回迭代器下一個元素

Out[3]: 'root:x:0:0:root:/root:/bin/bash\n'

In [4]: f1.next()

Out[4]:'bin:x:1:1:bin:/bin:/sbin/nologin\n'

In [5]: f1.close()     #close()關閉檔案    

In [6]: f1.next()    #檔案關閉時迭代器元素指向無法使用

---------------------------------------------------------------------------

ValueError                                Traceback (mostrecent call last)

<ipython-input-6-4a9d57471e88> in<module>()

----> 1 f1.next()

ValueError: I/O operation on closed file

In [7]: f1 = open('/etc/passwd','r')

#返回檔案描述符,0標準輸入,1,標註輸出,2,標準錯誤輸出

In [8]: f1.fileno()       #使用fileno()檢視檔案描述符 

Out[8]: 3

In [9]: f1.fileno()

Out[9]: 3

In [10]: f1.readline() #使用readline()成員函式讀一行檔案,注意檔案位置會偏移到下一行  

Out[10]:'root:x:0:0:root:/root:/bin/bash\n'

In [11]: f1.readline()   

Out[11]:'bin:x:1:1:bin:/bin:/sbin/nologin\n'

In [12]: f1.readlines() #使用readlines()函式讀取所有行並返回一個列表

Out[12]:

['daemon:x:2:2:daemon:/sbin:/sbin/nologin\n',

 'adm:x:3:4:adm:/var/adm:/sbin/nologin\n',

 'lp:x:4:7:lp:/var/spool/lpd:/sbin/nologin\n',

...,

 'redis:x:495:492:Redis DatabaseServer:/var/lib/redis:/sbin/nologin\n']

In [13]: f1.readline()

Out[13]: ''

In [14]: f1.tell()    #tell()函式返回當前檔案指標

Out[14]: 1966

In [15]: f1.seek(0)  #seek(0)重新指定檔案開始查詢位置,從頭部開始。

In [16]: f1.tell()

Out[16]: 0

In [17]: f1.readline()

Out[17]:'root:x:0:0:root:/root:/bin/bash\n'

In [18]: f1.seek(0)

In [19]: f1.read(10)

Out[19]: 'root:x:0:0'

In [20]: f1.tell()

Out[20]: 10

In [21]: f1.next()

Out[21]: ':root:/root:/bin/bash\n'

In [22]: f1.next()

Out[22]: 'bin:x:1:1:bin:/bin:/sbin/nologin\n'

In [23]: f1.name     #返回檔名

Out[23]: '/etc/passwd'

例2:讀寫模式開啟/tmp/passwd

In [1]: f1 = open('/tmp/passwd','r+')

In [2]: f1.next()

Out[2]: 'root:x:0:0:root:/root:/bin/bash\n'

In [3]: f1.tell()

Out[3]: 1966

In [4]: f1.seek(0,2)

In [5]: f1.tell()

Out[5]: 1966

In [6]: f1.write('new line,test.\n')   #使用write()函式在檔案末尾新增一行

In [7]: f1.tell()

Out[7]: 1981

In [8]: f1.close()

In [9]: exit

[[email protected] ~]# tail -n 2 /tmp/passwd

redis:x:495:492:Redis DatabaseServer:/var/lib/redis:/sbin/nologin

new line,test.

#末尾新增成功

例3:寫讀模式開啟一個新檔案/tmp/test.unl,並寫入內容

In [1]: f2 = open('/tmp/test.unl','w+')

In [2]: f2.write('hello,world!\nhow areyou\n')

In [3]: f2.close()

[[email protected] ~]# cat /tmp/test.unl

hello,world!

how are you

例4:各種模式下檔案開啟方式異同

In [1]: f2 = open('/tmp/test.unl','w+')

In [2]: f2.write('hello,world!\nhow areyou\n')

In [3]: f2.close()

#寫讀模式下,預設以寫模式開啟檔案,檔案不存在會新建

In [4]: f3 = open('/tmp/1test.txt','r')

---------------------------------------------------------------------------

IOError                                   Traceback(most recent call last)

<ipython-input-1-8ead05602c24> in<module>()

----> 1 f3 = open('/tmp/1test.txt','r')

IOError: [Errno 2] No such file ordirectory: '/tmp/1test.txt'

#讀模式下,開啟一個不存在的檔案會引發IOError

In [5]: f3 = open('/tmp/tmp1.txt','r+')

---------------------------------------------------------------------------

IOError                                   Traceback(most recent call last)

<ipython-input-1-542f9a700881> in<module>()

----> 1 f3 = open('/tmp/tmp1.txt','r+')

IOError: [Errno 2] No such file ordirectory: '/tmp/tmp1.txt'

#讀寫模式下,開啟一個不存在的檔案同樣會引發IOError,因為讀寫模式預設以讀模式開啟,所以檔案必須存在。

In [6]: f3 = open('/tmp/tmp.txt','a')

In [7]: f1.isatty()  #是否是tty終端檔案

Out[7]: False

In [8]: f3.close()

In [9]: exit

In [1]: f3 = open('/tmp/tmp.unl','a')

#附加模式下開啟一個不存在的檔案並寫入內容,均不會報錯,所以該模式下開啟一個不存在的檔案會新建。

In [3]: f3.write('hello,world!\nhow areyou\n')

In [4]: f3.flush()

In [5]: f3.readline()

---------------------------------------------------------------------------

IOError                                   Traceback(most recent call last)

<ipython-input-5-abe2a9ccc8b5> in<module>()

----> 1 f3.readline()

IOError: File not open for reading

#讀檔案內容時觸發IOError,所以附加模式下,檔案並未開啟,寫入時只是把內容追加到結尾處。

In [6]: f4 = open('/tmp/tmp2.unl','a+')

In [7]: f4.write('hello,world!\nhow areyou\n')

In [8]: f4.flush()

In [9]: f4.readline()

Out[9]: ''

In [11]: f4.tell()

Out[11]: 25

In [12]: f4.seek(0)

In [13]: f4.readline()

Out[13]: 'hello,world!\n'

In [14]: f4.readline()

Out[14]: 'how are you\n'

#附加讀寫模式下,寫入檔案並重新整理記憶體讀寫檔案寫入內容,不會引發IOError,所以附加模式下,檔案開啟。

例5:檔案成員函式在for迴圈中的應用

In [1]: s1 = 'abc'

In [2]: s2 = 'xy'

In [3]: s1 + s2

Out[3]: 'abcxy'

In [4]: s1.join(s2)

Out[4]: 'xabcy'

In [5]: s2 = 'xyzk'

In [6]: s1.join(s2)

Out[6]: 'xabcyabczabck'

In [7]: s1 + '\n' 

Out[7]: 'abc\n'

In [8]: f1 = open('/tmp/test0526.txt','w+')

In [9]: for line in ( i**2 for i inrange(1,11) if i%2 == 0):

  ....:    f1.write(str(line)+'number_test\n')

  ....:    

In [10]: f1.flush()

[[email protected] tmp]# cat test0526.txt

4number_test

16number_test

36number_test

64number_test

100number_test

例6、常見成員方法

In [1]: f1 = open('/tmp/passwd','w+')

In [2]: f1.isatty()    #檔案是否是終端tty檔案

Out[2]: False

In [3]: f1.encoding #檔案編碼。如果沒有使用任何編碼該值為none

In [4]: f1.softspace

Out[4]: 0

In [5]: f1.closed   #檔案是否開啟

Out[5]: False

In [6]: f1.close() 

In [7]: f1.closed 

Out[7]: True


相關推薦

Python函式open()&檔案屬性方法

Python檔案物件開啟模式及其屬性方法詳解1、檔案系統和檔案檔案系統:檔案系統是OS用於明確磁碟或分割槽上的檔案的方法和資料結構,即在磁碟上組織檔案的方法檔案:儲存在某種長期儲存裝置或臨時儲存裝置中的一段資料流,並且受計算機檔案系統管理。概括來講,檔案是計算機中有OS管理的

python函式 sorted

sorted作為python的內建全域性方法,用於可迭代序列的排序。   sorted函式接受3個引數: sorted(iterable,key,reverse)sorted函式有以下特點:1)對列表排序,返回的物件不會改變原列表 >>> list =[1,2,3,

(轉)Python函式進階之“屬性(property())”

原文:https://blog.csdn.net/GeekLeee/article/details/78519767 版權宣告:本文為博主原創文章,未經博主允許不得轉載。 https://blog.csdn.net/GeekLeee/article/details/78519767屬性函式(property

Python函式(BIF)查詢(附中文說明)

我們知道,Python 直譯器內建了一些常量和函式,叫做內建常量(Built-in Constants)和內建函式(Built-in Functions),來實現各種不同的特定功能,在我的另外一篇部落格中 第8章:Python計算生態  講述了一些常用的內建函式的使用方法,但是隨著Py

Python函式總結及

………………吧啦吧啦……………… 2個多月來,將3.5版本中的68個內建函式,按順序逐個進行了自認為詳細的解析。為了方便記憶,將這些內建函式進行了如下分類: 數學運算(7個) 型別轉換(24個) 序列操作(8個) 物件操作(7個) 反射操作(8個) 變數操

Python函式【翻譯自python3.6官方文件共68個】

翻譯源 來自:https://docs.python.org/3/library/functions.html  abs(x) 返回一個數的絕對值。引數可以是一個整數或一個浮點數。若引數是複數,返回複數的模 all(iterable) 若 可迭代物件中所有元素為真

Python函式——總結篇

#字串可以提供的引數 's' None >>> format('some string','s') 'some string' >>> format('some string') 'some string' #整形數值可以提供的引數有 'b' 'c' 'd' 'o'

Python函式

         置頂   內建函式詳解 https://docs.python.org/3/library/functions.html?highlight=built#ascii        此文參考了別人整理好的東西(地址:http://www.cnblogs.co

Python 函式sorted和itemgetter, attrgetter

Python lists have a built-in sort() method that modifies the list in-place and a sorted() built-in function that builds a new sorted list

Python標準庫:函式open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=T

                本函式是開啟一個檔案並返回檔案物件。如果檔案不能開啟,丟擲異常OSError。引數file是一個字串表示的檔名稱,或者一個數組表示的檔名稱。檔名稱可以是相對當前目錄的路徑,也可以是絕對路徑表示。引數mode是指明開啟檔案的模式。預設值是’r’,表示使用文字的方式開啟檔案來讀取。

利用python下載器-快速分享檔案

一、任務場景: 工作中需要將伺服器上的某些檔案傳給對應的同事,如果臨時去搭建檔案伺服器或者配置,操作起來不太方便 二、比如臨時需要分享/tools這個目錄的檔案,操作方法如下: 1、採用http的方式進行分享 a) python2的版本中 # cd /tools #&nb

Python函式map

簡介 map()是 Python 內建的高階函式,它接收一個函式 func 和一個 list,並通過把函式 func依次作用在 list 的每個元素上,得到一個新的 list 並返回。 一、當list只有一個時 當list只有一個時,將函式func作用於這個list的每個元素上

【轉】Python 函式 locals() 和globals()

Python 內建函式 locals() 和globals() 轉自: https://blog.csdn.net/sxingming/article/details/52061630

python ----函式

def abs(*args, **kwargs)返回引數的絕對值。 a = -5 print(abs(a)) #列印結果:5     all(*args, **kwargs)all() 函式用於判斷給定的可迭代引數 iterable 中的所有元素是否都為

Python 函式 lambda、filter、map、reduce

轉載自:http://www.cnblogs.com/feeland/    Python 內建了一些比較特殊且實用的函式,使用這些能使你的程式碼簡潔而易讀。   下面對 Python 的 lambda、filter、map、reduce 進行初步的學習。red

Python 中 apply 函式(關鍵詞:Python/函式/apply)

>>> apply <built-in function apply> >>> def a(): ... print 'i am a' ... >>> apply(a) i am a >>> de

Python之路Python函式、zip()、max()、min() Python之路Python函式、zip()、max()、min()

Python之路Python內建函式、zip()、max()、min() 一、python內建函式 abs() 求絕對值 例子 print(abs(-2)) all() 把序列中每一個元素做布林運算,如果全部都是true,就返回true,

python函式,這一波看完後又可以少些很多程式碼了 python函式大全

python內建函式大全   python內建函式 最近一直在看python的document,打算在基礎方面重點看一下python的keyword、Build-in Function、Build-in Constants、Bui

Python函式方法靜態方法例項化方法學習

靜態方法 class C(object): @staticmethod def f(): print('runoob'); C.f(); # 靜態方法無需例項化 cobj = C() cobj.f() # 也可以例項化後

python函式(程式設計)

''' 10.輸入10個數,將列表中元素逆置後輸出 ''' l=[1,2,3,4,5,6,7,8,9,10] # -1 -2 -3 從右到左讀取 不改變原先集合順序 # 1-10 2-9 3-8 交換元素 改變原先集合順序 # reverse() i=-1 while i>=-10: