溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

Python打開文件、文件讀寫操作、with方式、文件常用函數(shù)實(shí)例分析

發(fā)布時(shí)間:2020-09-16 15:27:02 來源:腳本之家 閱讀:129 作者:隨風(fēng)行云 欄目:開發(fā)技術(shù)

本文實(shí)例講述了Python打開文件、文件讀寫操作、with方式、文件常用函數(shù)。分享給大家供大家參考,具體如下:

打開文件:

在python3中,打開文件的函數(shù)是:

open(file, mode='r', buffering=None, encoding=None, errors=None, newline=None, closefd=True)

參數(shù)說明:

file--文件名
mode—打開模式,默認(rèn)只讀模式
buffering--如果buffering的值被設(shè)為0,就不會(huì)有寄存。如果buffering的值取1,訪問文件時(shí)會(huì)寄存行。如果將buffering的值設(shè)為大于1的整數(shù),表明了這就是的寄存區(qū)的緩沖大小。如果取負(fù)值,寄存區(qū)的緩沖大小則為系統(tǒng)默認(rèn)。
encoding—打開文件的編碼方式 

模式介紹:

r:只讀模式(默認(rèn))

w :只寫模式,如果文件不存在就創(chuàng)建,如果存在,寫入的數(shù)據(jù)會(huì)覆蓋原來的數(shù)據(jù)

b :二進(jìn)制模式

t :文本模式

+:可寫可讀模式

a:追加模式,如果文件存在則文件指針指向文件末尾(追加數(shù)據(jù)),如果不存在就創(chuàng)建

r+:讀追加模式,先讀,再追加

w+:寫讀模式,先寫,意味著原本內(nèi)容丟失,再讀。  

  • 如果對(duì)于含有非ascll字符的文件,必須使用encoding,否則會(huì)拋異常:

Python打開文件、文件讀寫操作、with方式、文件常用函數(shù)實(shí)例分析

print("r".center(50,'-'))
f=open("file.txt",encoding="utf-8")
print(f.read())
f.close()
-----------------
運(yùn)行結(jié)果:
my
sas
aaa
fsafsa
中文
中文
葫蘆娃

文件使用完畢后必須關(guān)閉: 文件指針.close() 


文件操作:

讀操作:

讀取文件內(nèi)容如下:

Python打開文件、文件讀寫操作、with方式、文件常用函數(shù)實(shí)例分析

  • reads()是讀出全部內(nèi)容
print("r".center(50,'-'))
f=open("file.txt",encoding="utf-8")
print(f.read())
f.close()
---------------------------
運(yùn)行結(jié)果:
my
sas
aaa
fsafsa
中文
中文
葫蘆娃
  • readline()是讀出一行
print("r".center(50,'-'))
f=open("file.txt",encoding="utf-8")
print(f.readline())
f.close()

-----------
運(yùn)行結(jié)果:
my
  • readlines()是讀出全部內(nèi)容,并整理成一個(gè)列表
print("r".center(50,'-'))
f=open("file.txt",encoding="utf-8")
print(f.readlines())
f.close()




#------------------------r-------------------------
#運(yùn)行結(jié)果:
['my\n', 'sas\n', 'aaa\n', 'fsafsa\n', '中文\n', '中文\n', '葫蘆娃\n', '\n']
  • r+模式會(huì)根據(jù)讀的內(nèi)容來決定指針的位置
print("r".center(50,'-'))
f=open("file.txt","r+",encoding="utf-8")
# print(f.readline())
f.write("hello mike")
f.close()

結(jié)果:

Python打開文件、文件讀寫操作、with方式、文件常用函數(shù)實(shí)例分析

 

print("r".center(50,'-'))
f=open("file.txt","r+",encoding="utf-8")
print(f.readline())
f.write("hello mike")
f.close()

新結(jié)果:

Python打開文件、文件讀寫操作、with方式、文件常用函數(shù)實(shí)例分析 

寫操作:

  • write():將一個(gè)字符串寫入文件
myfile=open("myfile1","wb")
myfile.write(b"nnnnnn")
myfile.write("my葫蘆娃".encode("utf-8"))
myfile.close()
  • writelines(可迭代對(duì)象) 將一個(gè)可迭代對(duì)象寫入文件
myfile=open("myfile1","wb")
myfile.write(b"nnnnnn")

myfile.writelines([b'1',b'2',b'3',b'4'])
myfile.close()
  • 當(dāng)需要寫完之后即時(shí)讀出來時(shí),使用w+,然后將文件指針置回文件頭:
myfile=open("myfile1","wb+")
myfile.write(b"nnnnnn")
myfile.seek(0)
print(myfile.read())
myfile.close()
      • 如果是需要讀出特定位置,可以使用變量來記錄位置
myfile=open("myfile1","wb+")
myfile.write(b"1nnnnnn")
site=myfile.tell()
myfile.write(b"2nnnnnn")
myfile.seek(site)##讀出后一段
print(myfile.read())
myfile.close()

with:

  • 為了便捷的關(guān)閉文件,python增加了with功能,當(dāng)with體執(zhí)行完將自動(dòng)關(guān)閉打開的文件:
with open("file.txt","r+",encoding="utf-8") as f:##將自動(dòng)執(zhí)行f.close()
 print(f.tell())
 f.write("金剛")
 for line in f:
  print(line,end="")
  • 可以同時(shí)打開多個(gè)文件:
with open("file.txt",'r') as f ,\
open("file.new",'r') as m:
 print(f.read(),m.read())

文件常用函數(shù):

file.close():關(guān)閉文件。關(guān)閉后文件不能再進(jìn)行讀寫操作

file.seek(offset[, whence]):設(shè)置文件當(dāng)前位置

file.tell():返回文件當(dāng)前位置。

myfile=open("myfile1","wb+")
myfile.write(b"1nnnnnn")
site=myfile.tell()
myfile.write(b"2nnnnnn")
myfile.seek(site)##讀出后一段
print(myfile.read())
myfile.close()

file.flush():刷新文件內(nèi)部緩沖,立即把內(nèi)部緩沖區(qū)的數(shù)據(jù)寫入文件,因?yàn)椴⒉皇邱R上將文件

import time
myfile=open("myfile1","wb+")
myfile.write(b"1nnnnnn")
time.sleep(10)
# myfile.flush()
myfile.write(b"2nnnnnn")
myfile.close()

上述代碼,直到程序運(yùn)行完成才一次性寫入“1nnnnnn2nnnnnn”

import time
myfile=open("myfile1","wb+")
myfile.write(b"1nnnnnn")
myfile.flush()
time.sleep(10)
myfile.write(b"2nnnnnn")
myfile.close()

上述代碼,可以看到,在程序sleep之前就已經(jīng)寫入了“1nnnnnn”

file.truncate([size]):截取文件,從文件開頭,截到指定位置,會(huì)覆蓋原文件。

文件內(nèi)容:

Python打開文件、文件讀寫操作、with方式、文件常用函數(shù)實(shí)例分析

print("r".center(50,'-'))
f=open("file.txt","r+",encoding="utf-8")

print(f.readline())
print("----truncate()-------")
print(f.tell())
m=f.tell()
f.truncate(m)#內(nèi)容從0位置截?cái)嗟街付ㄎ恢?,不論?dāng)前光標(biāo)位置
f.close()

執(zhí)行后,文件內(nèi)容:

Python打開文件、文件讀寫操作、with方式、文件常用函數(shù)實(shí)例分析

更多關(guān)于Python相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Python文件與目錄操作技巧匯總》、《Python文本文件操作技巧匯總》、《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》及《Python入門與進(jìn)階經(jīng)典教程》

希望本文所述對(duì)大家Python程序設(shè)計(jì)有所幫助。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI