7.打開文件、文件讀寫操作、with方式、文件常用函數



打開文件:

在python3中,打開文件的函數是:

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

參數說明:

file--文件名
mode—打開模式,默認只讀模式
buffering--如果buffering的值被設為0,就不會有寄存。如果buffering的值取1,訪問文件時會寄存行。如果將buffering的值設為大於1的整數,表明了這就是的寄存區的緩沖大小。如果取負值,寄存區的緩沖大小則為系統默認。
encoding—打開文件的編碼方式 

模式介紹:

r:只讀模式(默認)

w :只寫模式,如果文件不存在就創建,如果存在,寫入的數據會覆蓋原來的數據

b :二進制模式

t :文本模式

+:可寫可讀模式

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

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

w+:寫讀模式,先寫,意味着原本內容丟失,再讀。

 

 

 

  • 如果對於含有非ascll字符的文件,必須使用encoding,否則會拋異常:

image

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

 

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

 


文件操作:

 

讀操作:

讀取文件內容如下:

image

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

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




------------------------r-------------------------
運行結果:
['my\n', 'sas\n', 'aaa\n', 'fsafsa\n', '中文\n', '中文\n', '葫蘆娃\n', '\n']

 

  • r+模式會根據讀的內容來決定指針的位置
print("r".center(50,'-'))
f=open("file.txt","r+",encoding="utf-8")
# print(f.readline())
f.write("hello mike")
f.close()

結果:

image

 

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

新結果:

image

 

 

 

 

寫操作:

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

myfile.writelines([b'1',b'2',b'3',b'4'])
myfile.close()
  • 當需要寫完之后即時讀出來時,使用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:

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

文件常用函數:

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

 

file.seek(offset[, whence]):設置文件當前位置

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

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():刷新文件內部緩沖,立即把內部緩沖區的數據寫入文件,因為並不是馬上將文件

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

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

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

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

 

 

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

文件內容:

image

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)#內容從0位置截斷到指定位置,不論當前光標位置
f.close()

 

執行后,文件內容:

image


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM