【13】Python之常用文件操作

File對象使用open函數來創建,下表列出file對象常用的函數。

序號

方法

描述

1

file.close()

關閉文件。關閉文件後不能在進行讀寫。注:文件打開後別忘記關閉。

2

file.flush()

刷新文件內部緩衝,直接把內部緩衝區的數據立刻寫入文件,而不是被動的等待緩衝區的寫入。(緩衝區好比PC機的內存)

3

file.fileno()

返回一個整型的文件描述(file descriptor FD整型),可以用在如OS模塊的read方法等一些底層操作上

4

file.isatty()

如果文件連接到一個終端上返回True,否則False

5

file.next()

返回文件下一行

6

file.read([size])

從文件讀取指定的字節數,如果未給定或爲負則讀取所有。

7

file.readline([size])

讀取整行,包括\n字符

8

file.readlines([sizeint])

讀取所有行並返回列表,若給定sizeint>0,返回總和大約爲sizeint字節的行,實際讀取值肯能比sizeint較大,因爲需要填充緩衝區

9

file.seek(offset[, whence])

設置文件當前位置

10

file.tell()

返回文件當前位置

11

file.truncate([size])

從文件的首行首字符開始截斷,截斷文件爲size個字符,五size表示從當前位置截斷;截斷之後V後面的所有字符被刪除,其中Windows系統下的換行代表2個字符大小。

12

file.write(str)

將字符串寫入文件,沒有返回值。

13

file.writelines(sequence)

向文件寫入一個序列字符串列表,如果需要換行則要自己加入每行的換行符。

 

 

file.close()

概述:關閉文件。關閉文件後不能在進行讀寫。注:文件打開後別忘記關閉。

f=open('so_file',encoding="utf-8")  #打開文件,並讀取。Windows上默認字符集GDK,所以這裏指定了字符集,不然會報錯。(#UnicodeDecodeError: 'gbk' codec can't decode byte 0x80 in position 106: illegal multibyte sequence
data=f.read()  #將讀取的內容賦值給data
print(data)
f.close()  #一定要關閉,纔是一個完成的讀取文件方式。

 

 

打開文件的模式有:

  • r,只讀模式(默認)。

  • w,只寫模式。【不可讀;不存在則創建;存在則刪除內容;】

  • a,追加模式。【可讀; 不存在則創建;存在則只追加內容;】

"+" 表示可以同時讀寫某個文件

  • r+,可讀寫文件。【可讀;可寫;可追加】

  • w+,寫讀

  • a+,同a

"U"表示在讀取時,可以將 \r \n \r\n自動轉換成 \n (與 r 或 r+ 模式同使用)

  • rU

  • r+U

"b"表示處理二進制文件(如:FTP發送上傳ISO鏡像文件,linux可忽略,windows處理二進制文件時需標註)

  • rb

  • wb

  • ab

     

    File.flush()

    概述:用來刷新緩衝區的,即將緩衝區的數據立刻寫入文件,同時清空緩衝區,不需要是被動的等待輸出緩衝區寫入。

    一般情況下文件關閉後會自動刷新緩衝區,但有時你需要在關閉前刷新她,這時就可以使用flush方法。

f=open('so_file','wb')  #打開文件,並讀取。
# data=f.read()  #將讀取的內容賦值給data
# print(data)
print("file name is :",f.name)
f2=f.flush()
# print(f2)
f.close()

運行結果:

file name is : so_file

注意:二進制模式下,不支持編碼參數

 

緩衝flush作用效果圖:(執行有驚喜)

import sys,time
f=open('so_file','r+',encoding="utf-8")
for i in range(20):
    sys.stdout.write("#")
    sys.stdout.flush()
    time.sleep(0.1)

運行結果:

####################

 

File.fileno()

概述:返回一個整型的文件描述(file descriptor FD整型),可以用在如OS模塊的read方法等一些底層操作上

f=open('so_file','wb')  #打開文件,並讀取。
# data=f.read()  #將讀取的內容賦值給data
# print(data)
print("file name is :",f.name)
# f2=f.flush()
fidd=f.fileno()
print("file》》》",fidd)  #返回文件描述符
f.close()

運行結果:

file name is : so_file

file》》》 3

 

File.isatty()

概述:如果文件連接到一個終端上返回True,否則False

f=open('so_file','wb')  #打開文件,並讀取。
# data=f.read()  #將讀取的內容賦值給data
# print(data)
print("file name is :",f.name)
fin=f.isatty()
print("file》》》",fin)
f.close()

運行結果:

file name is : so_file

file》》》 False

 

File.readline()

概述:讀取整行,包括\n字符

f=open('so_file','r+',encoding="utf-8")
print("file name is :",f.name)
# for index in range(5):
#     line = next(fo)
#     print ("第 %d 行 - %s" % (index, line))
data=f.readline() #不填默認讀取一行
print("讀取首行:",data)
data1=f.readline(5)  #讀取N個字符
print("讀取%s個字符" %(data1),data1)
f.close()

運行結果:

file name is : so_file

讀取首行: Somehow, it seems the love I knew was always the most destructive kind

 

讀取Yeste個字符 Yeste

 

File.readlines()

概述:用於讀取所有行(直到結束符 EOF)並返回列表,該列表可以由 Python for... in ... 結構進行處理。 如果碰到結束符 EOF 則返回空字符串。
如果碰到結束符 EOF 則返回空字符串。

f=open('so_file','r+',encoding="utf-8")
print("file name is :",f.name)
data=f.readlines()  #全部打印結尾加\n
print(data)
f.close()

 

第十行不打印

f=open('so_file','r+',encoding="utf-8")
for index,info in enumerate(f.readlines()):
    if index==9:
        print('--------GO-------')
        continue
    print(info.strip())
f.close()

高效的循環方法:

f=open('so_file','r+',encoding="utf-8")
count=0
for line in f:
    if count==9:
        print('---------GO--------')
        count +=1
        continue
    print(line)
    count +=1

 

File.tell()

概述:反饋文件當前位置,即文件指針當前位置

f=open('so_file','r+',encoding="utf-8")
data=f.readline()
print("讀取數據爲:%s"%(data))
data2=f.tell()
print("當前位置:%s" %(data2))

運行結果:

讀取數據爲:Somehow, it seems the love I knew was always the most destructive kind

 

當前位置:72  #read結束,全文72

 

File.seek()

概述:指針移動到之指定位置

 

File.truncate()

概述:用於從文件的首行首字符開始截斷,截斷文件爲 size 個字符,無 size 表示從當前位置截斷;截斷之後 V 後面的所有字符被刪除,其中 Widnows 系統下的換行代表2個字符大小。

.truncate()什麼都不寫,清空文件。指定數字就會截斷個數。

 

 

File.write()

修改部分值,寫入新文件。

f=open('so_file','r',encoding="utf-8")
f_new=open('so_file2','w',encoding="utf-8")
for line in f:
    if "生命的滋味是甜的" in line:
        line=line.replace("生命的滋味是甜的","生命的滋味是幸福的")
    f_new.write(line)
f.close()
f_new.close()

運行結果:

So_file文件內容

Somehow, it seems the love I knew was always the most destructive kind
不知爲何,我經歷的愛情總是最具毀滅性的的那種
Yesterday when I was young
昨日當我年少輕狂
The taste of life was sweet
生命的滋味是甜的
As rain upon my tongue
就如舌尖上的雨露
I teased at life as if it were a foolish game
我戲弄生命 視其爲愚蠢的遊戲
The way the evening breeze
就如夜晚的微風
May tease the candle flame

So_file2文件內容(新文件)

Somehow, it seems the love I knew was always the most destructive kind
不知爲何,我經歷的愛情總是最具毀滅性的的那種
Yesterday when I was young
昨日當我年少輕狂
The taste of life was sweet
生命的滋味是幸福的
As rain upon my tongue
就如舌尖上的雨露
I teased at life as if it were a foolish game
我戲弄生命 視其爲愚蠢的遊戲
The way the evening breeze
就如夜晚的微風
May tease the candle flame

 

 

 


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章