- [ ] 對於檔案操作,python提供如下功能
## 唯讀形式讀檔案
def file_r():
f = open("./mydirtest/1.txt", mode="r", encoding="utf-8")
print(f.read())
f.close()
## 寫入檔案,要先將1.txt的檔案內容清空之後,在進行寫入,不可讀
def file_w():
f = open("./mydirtest/1.txt", mode="w", encoding="utf-8")
f.write("寫入檔案資訊")
f.close()
## 在原始檔案上追加寫入內容,不可讀
def file_a():
f = open("./mydirtest/1.txt", mode="a", encoding="utf-8")
f.write("寫入檔案資訊")
f.close()
## 建立檔案並寫入內容,不可讀
def file_x():
f = open("./mydirtest/2.txt", mode="x", encoding="utf-8")
f.write("寫入檔案資訊")
f.close()
if __name__ == '__main__':
file_r()
file_w()
file_a()
file_x()
##增強型讀寫檔案,同時存在可讀屬性
## 增強行讀寫
def file_rpuls():
r = open("./mydirtest/1.txt", mode="r+", encoding="utf-8")
print(r.read())
r.write("\n增加一行新資料\n")
r.close()
## 增強型追加寫入
def file_apuls():
r = open("./mydirtest/1.txt", mode="a+", encoding="utf-8")
print(r.read())
r.write("\n增加一行新資料\n")
r.close()
##增強型寫入
def file_wpuls():
r = open("./mydirtest/1.txt", mode="w+", encoding="utf-8")
print(r.read())
r.write("\n增加一行新資料\n")
r.close()
def for_file():
with open("./mydirtest/1.txt", mode="r+", encoding="utf-8") as file:
for line in file:
print(line)
## with 直接對檔案進行操作關閉,不用在單獨編寫close 函式 ,需要進行as 別名,不然無法操作檔案
def pointer():
with open("./mydirtest/1.txt",mode="r+",encoding="utf-8") as file:
print(file.tell()) ###獲取當前檔案位置
file.seek(3) ### 移動位置,設定當前的位元組為止已輸出展示
print(file.read(1))
print(file.tell())
關閉檔案。關閉後檔案不能再進行讀寫操作。
2 file.flush()
重新整理檔案內部緩衝,直接把內部緩衝區的資料立刻寫入檔案, 而不是被動的等待輸出緩衝區寫入。
3 file.fileno()
返回乙個整型的檔案描述符(file descriptor fd 整型), 可以用在如os模組的read方法等一些底層操作上。
4 file.isatty()
如果檔案連線到乙個終端裝置返回 true,否則返回 false。
5 file.next()
返回檔案下一行。
6 file.read([size])
從檔案讀取指定的位元組數,如果未給定或為負則讀取所有。
7 file.readline([size])
讀取整行,包括 「\n」 字元。
8 file.readlines([sizeint])
讀取所有行並返回列表,若給定sizeint>0,返回總和大約為sizeint位元組的行, 實際讀取值可能比 sizeint 較大, 因為需要填充緩衝區。
9 file.seek(offset[, whence])
設定檔案當前位置
10 file.tell()
返回檔案當前位置。
11 file.truncate([size])
從檔案的首行首字元開始截斷,截斷檔案為 size 個字元,無 size 表示從當前位置截斷;截斷之後後面的所有字元被刪除,其中 widnows 系統下的換行代表2個字元大小。
12 file.write(str)
將字串寫入檔案,返回的是寫入的字元長度。
13 file.writelines(sequence)
向檔案寫入乙個序列字串列表,如果需要換行則要自己加入每行的換行符。
python檔案操作2
讀寫 定位 f.seek 偏移量,0,1,2 0,開頭,預設。1,當前位置。2,檔案末尾。f.tell 檢視當前指標的位置。f open a.txt rb print f.tell f.seek 2 2 print f.tell print f.read print f.tell f.close 讀...
Python檔案操作(2)
os.path.dirname path 返回path引數中的路徑名稱和字串 os.path.basename path 返回path引數中的檔名 os.path.splot path 返回引數的路徑名稱和檔名組成的字串元組 import os totalsize 0 os.chdir f pyth...
Python基礎 檔案操作
使用 open 能夠開啟乙個檔案,open 的第乙個引數為檔名和路徑 my file.txt 第二個引數為將要以什麼方式開啟它,比如w為可寫方式.如果計算機沒有找到 my file.txt 這個檔案,w 方式能夠建立乙個新的檔案,並命名為 my file.txt 例項 text tthis is m...