python之檔案讀寫

2021-10-12 18:29:19 字數 1386 閱讀 1384

python檔案讀寫

檔案讀取:

data =

open

("baotuquan"

,'r'

,encoding=

'utf-8'

).read(

)print

(data)

輸出前10行,第九行修改:

for line in f:

count ==

0if count ==9:

print

('------fen------'

) count +=

1continue

print

(line)

count +=

1

1.

f = open(『baotuquan2』,『w』,encoding=『utf-8』)#f為記憶體物件,檔案控制代碼,包含檔名,字符集,大小,在硬碟上的起始位置,寫檔案是重新建立,若之前存在同名檔案,將清除裡面的內容

2.

f.write(『老舍』)#寫檔案不能同時讀

3.

『r』:唯讀,『w』:只寫,『a』:追加,將文字加到後面,『r+』:讀寫,開啟後追加,『w+』:寫讀,『a+』:追加讀,『ru』/『r+u』:將\r\n和\r和\n全部變成\n

4.

f.close()

5.

#游標print(f.read(5))

print(f.tell())

f.seek(0)#游標回到其他位置

f.flush()#等快取滿了一次性寫到記憶體裡,強制刷,實時刷到硬碟上

f.truncate(10)#從頭開始截10個

6.

二進位制:

f =

open

('baotuquan'

,'wb'

)print

(f.readline())

f.write(

'hello binanry\n'

.encode())

f.close(

)

flush使用:

import sys,time

for i in

range(20

):sys.stdout.write(

'#')

sys.stdout.flush(

) time.sleep(

0.1)

python之讀寫檔案

fr open readfile.txt r fw open writefile.txt w print fr.readline print fr.tell print fr.readlines fw.write write line fw.close fr.seek 0,0 第乙個引數代表位元組數...

Python之檔案讀寫

本文介紹python語言中的對於檔案的讀寫等操作。本文使用python3 首先是對檔案的操作流程為 1.開啟檔案,得到檔案控制代碼並賦值給乙個變數 2.通過控制代碼對檔案進行操作 3.關閉檔案 對於檔案的操作就離不開open 函式 這個函式是python的io模組中的乙個內建函式 首先建議使用hel...

python之讀寫檔案

1.讀取檔案資料,檔案必須存在才可以讀且如要讀取的檔案不和當前.py在同乙個包下,需要特別指定此檔案路徑才行 f open test.txt encoding utf 8 填寫檔案路徑,開啟檔案 res f.read 讀取檔案 print res 顯示f.close 2.寫入後讀取 寫入資料 fw ...