學習python的檔案操作

2021-10-11 09:06:52 字數 1566 閱讀 9352

file.close():關閉檔案。關閉後檔案不能再進行讀寫操作

file.flush():重新整理檔案內部緩衝,直接把內部緩衝區的資料立刻寫入檔案,而不是被動的等待輸出緩衝區寫入

file.fileno():返回乙個整型的檔案描述符(file descriptor fd整型),可以用在如os模組的read方法等一些底層操作

file.isatty():如果檔案鏈結到乙個終端裝置返回true,否則返回false

file.next():返回檔案下一行

file.read([size]):從檔案讀取制定的位元組數,如果未給定或為負則讀取所有

1 建立空檔案:os.mknod(「test.txt」)

2.直接開啟乙個檔案,如果檔案不存在則建立檔案:fp = open(「test.txt」,w)

關於open模式:

w 以寫方式開啟;

a 以追加模式開啟(從eof開始,必要時建立新檔案)

r+ 以讀寫模式開啟;

w+ 以讀寫模式開啟(參 w)

a+ 以讀寫模式開啟(參 a)

rb 以二進位制讀模式開啟;

wb 以二進位制寫模式開啟(參 w)

ab 以二進位制追加模式開啟(參 a)

rb+ 參r+

wb+ 參w+

ab+ 參a+

1.os.mkdir(『file』) 建立目錄;

複製檔案:

1.shutil.copyfile(『oldfile』,『newfile』) oldfile和newfile都只能是檔案;

2.shutil.copy(「oldfile」,「newfile」) oldfile只能是資料夾,newfile可以是檔案,也可以是目標目錄

複製資料夾:

1.shutil.copytree(「olddir」,「newdir」) olddir和newdir都只能是目錄,且newdir必須不存在;

重新命名檔案(目錄)

os.rename(「oldname」,「newname」)

移動檔案(目錄)

stutil.move(「oldpos」,「newpos」)

刪除檔案

os.remove(「file」)

刪除目錄

os.redir(「dir」)只能刪除空目錄

shutil.rmtree(「dir」) 空目錄,有內容的目錄都可以刪

轉換目錄

os.chdir(「path」) 換路徑

1 seek(offset,where) where=0從起始位置移動,1從當前位置移動,2從結束位置移動。當前換行時,會被換行截斷。

seek()返回值,故值為none;

2.tell(): 檔案的噹噹位置,即tell是獲得檔案指標位置,受seek、readline、read、readlines影響,不受truncate影響;

3.truncate(n): 從檔案的首行首字元開始截斷,截斷檔案為n個字元,無n表示從當前位置截斷;截斷之後n後面的所有字元被刪除,其中win下的換行代表 ,2個字元大小;

4.readline(n);讀放若干行,n表示讀放的最長位元組數。其中讀取的開始位置為tell()+1。 當n為空時,預設唯讀當前行的內容;

python學習 檔案的操作

with關鍵字來幫我們管理上下文 with open a.txt w as f pass with open a.txt r as read f,open b.txt w as write f data read f.read write f.write data 檔案的操作流程 1.開啟檔案,得到...

Python學習 檔案操作

python使用open來開啟資料流 data open data.txt 下面是乙個讀取乙個檔案,然後逐行輸出的 try data open data.txt for each line in data try role,line spoken each line.split 1 print ro...

Python學習筆記《檔案操作》

python的檔案操作容易上手,我選取了一些比較常用的。keep 開啟檔案 和c有點相像 f open friend.cpp 會讀取出來整個檔案的內容 小心記憶體不夠 f.read f.close with open friend.cpp as f f.read 逐行讀取 readlines 可以返...