Python之檔案操作

2021-09-11 01:34:23 字數 1259 閱讀 9677

一.檔案操作

1.open()函式和file()函式操作相似

filename = 'py_only_read.txt'

f = open(filename,mode='r',encoding='utf-8') --異常

traceback (most recent call last):

file "", line 1, in

typeerror: 'encoding' is an invalid keyword argument for this function

1.1 什麼編碼型別寫入的檔案,用什麼編碼開啟,預設可以不寫

1.2 開啟檔案的方式:

r  -- 唯讀方式開啟檔案,檔案不存在丟擲異常

w  -- 只寫方式開啟檔案,檔案存在內容被清空,不存在新建

a  -- 追加方式開啟檔案,檔案不存在會建立

rb -- 二進位制唯讀開啟檔案

wb -- 二進位制只寫開啟檔案

ab -- 二進位制追加開啟檔案

rw -- 讀寫方式開啟檔案,檔案存在則清空,不存在則報錯

r+ -- 讀寫方式開啟檔案,不存在則報錯

w+ -- 讀寫方式開啟檔案,檔案存在則清空,不存在則建立

a+ -- 讀以及追加寫入的方式開啟檔案

r+b -- 新增二進位制特性

w+b -- 同上

a+b -- 同上

2.檔案操作控制代碼方法介紹

close -- 關閉乙個開啟的檔案控制代碼

f.closed -- 判斷乙個檔案是否已經關閉

flush -- 立即將記憶體的資料寫入磁碟

mode -- 檔案開啟的模式

name -- 檔名

read -- 預設把檔案內容全部讀出,可設定大小,一次讀出指定字元數量內容

readline -- 一次讀出檔案的一行

readlines -- 讀出所有的內容,每一行是列表的乙個元素返回整個列表

seek -- 調整游標的位置(按位元組算)

tell -- 輸出當前游標的位置

write -- 寫入一行,需要自己新增換行符

writelines -- 把可迭代物件中的每個元素當成一行寫入檔案

3.with open方式開啟檔案(自動關閉,可以不用close方法)

with open('file1') as f: 開啟乙個檔案

...with open('file1') as f1,open('file2') as f2 ... 開啟多個檔案

...

Python之檔案操作

file open filename,mode mode預設為 r 例如file ope test.txt r 以讀的方式開啟檔案.檔案操作完畢記得關閉.file.close 其中,mode可以有以下選擇 檔案test.txt的內容為 11111111111 aaaaaaaaa 2222222222...

Python之檔案操作

使用open w 以寫入模式開啟,如果檔案存在將會刪除裡面的所有內容,然後開啟這個檔案進行寫入 a 以追加模式開啟,寫入到檔案中的任何資料將自動新增到末尾 fobj open home coder documents obama.txt 唯讀開啟 fobj fobj.close 關閉檔案 fobj ...

Python之檔案操作

建立目錄import os import errno defmkdir dir try os.makedirs dir except oserror as exc if exc.errno errno.eexist print the dir has been existed pass else r...