ython檔案IO讀寫

2021-08-28 07:00:13 字數 2218 閱讀 7284

一.文字資料

# 整個的檔案以字串的形式讀取

with open('somefile.txt', 'rt') as f:

data = f.read()

# 通過每行迭代讀取檔案

with open('somefile.txt', 'rt') as f:

for line in f:

# 處理讀取行的顯示

# 寫字元檔案到文字檔案,覆蓋掉文字中之前的檔案

with open('somefile.txt', 'wt') as f:

f.write("text1")

f.write("text2")

# 寫字元檔案到文字檔案,儲存之前的文字檔案在後面新增

with open('somefile.txt', 'at') as f:

f.write("text1")

f.write("text2")

3.臨時檔案的讀寫,需要引入包tempfile,臨時檔案內容沒有儲存,eg:

from tempfile import temporaryfile

with temporaryfile('w+t') as f:

f.write('hello world\n')

f.write('testing\n')

f.seek(0)

data = f.read()

print(data)

4.例項demo,test檔案之前儲存的內容為:"hello,jon!"

from tempfile import temporaryfile

def read():

with open('/home/jon/mydoc/test', 'rt') as f:

data = f.read()

print(data)

def read1():

f = open('/home/jon/mydoc/test', 'rt')

data = f.read()

print(data)

f.close()

def write():

with open('/home/jon/mydoc/test', 'wt', encoding='utf-8') as f:

f.write("hello,world!")

def write1():

with open('/home/jon/mydoc/test', 'at', encoding='utf-8') as f:

f.write("welcome python !")

with temporaryfile('w+t') as f:

f.write('hello world\n')

f.write('testing\n')

f.seek(0)

data = f.read()

print(data)

if __name__ == "__main__":

read()

print("------using 'rt' read-------")

read1()

print("-----using 'at' write--------")

write1()

read()

print("------using 'wt' write-------")

write()

read()

temporaryfile()

5.執行result

hello world

testing

hello,jon!

------using 'rt' read-------

hello,jon!

-----using 'at' write--------

hello,jon!

welcome python !

------using 'wt' write-------

hello,world!

process finished with exit code 0

注意事項:讀寫文字檔案一般來講是比較簡單的,但是也需要注意,例項中的 with 語句給被使用到的檔案建立了乙個上下文環境,但 with 控制塊結束時,檔案會自動關閉,如果不使用 with 語句,記得手動關閉檔案.

IO檔案讀寫

b表示二進位制模式訪問,但是對於linux或者unix系統來說這個模式沒有任何意義,因為他們把所有檔案都看做二進位制檔案,包括文字檔案 一.三種方法讀取檔案 方法1 open f open d hello.txt r 已讀的方式開啟,open只能讀檔案,不能讀資料夾 fp f.read print ...

檔案IO操作讀寫檔案

寫操作對應的有 put write等。寫操作的型別 ascii碼型別的可知字串 put put只能寫入一兩個字元,多了寫不了 include using namespace std intmain int args,char ar 二進位制型別寫檔案 write include using name...

IO流檔案讀寫

p1 開啟檔案 讀檔案 關閉檔案的典型方法 try f open d test.txt r print f.read finally if f f.close p2 推薦的簡潔寫法,不必顯示的關閉檔案描述符 open返回的物件在python中稱作file like 物件,可以是位元組流 網路流 自定...