Python檔案 資料夾操作總結

2021-10-07 12:57:14 字數 1203 閱讀 3000

python中對檔案、資料夾(檔案操作函式)的操作需要涉及到os模組和shutil模組

檔案操作:

關於open模式:

目錄操作:

複製檔案:

複製資料夾:

重新命名檔案(目錄)

移動檔案(目錄)

刪除檔案

刪除目錄

轉換目錄

以下以1個例子說明以上各個函式的作用

fso = open("f:\\a.txt",'w+')    '以w+方式,並非a方式開啟檔案,故檔案原內容被清空

print fso.tell()    '檔案原內容被清空,故此時tell()=0

fso.write("abcde\n")  '寫入檔案abcde\n,因為換行\n佔兩個字元,故共寫入7個字元

print fso.tell()  '此時tell()=7

fso.write("fghwm")  '又寫入檔案fghwm,故此時檔案共寫入7+5 =142個字元

print fso.tell()  '此時tell()=12 

fso.seek(1, 0)  '從起始位置即檔案首行首字元開始移動1個字元

print fso.tell()   『此時tell() =1

print  fso.readline()  '讀取當前行,即檔案的第1行,但是從第二個字元(tell()+1)開始讀,結果為:bcde。

'若換成for讀取整個檔案或read讀取整個檔案則結為bcdefghwm     

print fso.tell()   『因為readline此時tell() =7,

fso.truncate(8)  '從寫入後檔案的首行首字元開始階段,截斷為8個字元,即abcde\nf,即檔案的內容為:abcde\nf

print fso.tell()   『tell() 依舊為7,並為受truncate(8)影響,但是此時檔案內容為abcde\nf

print  fso.readline()  『從tell()+1=8開始讀取,讀取當前行內容:f

python檔案 資料夾操作

區別是glob列出的檔名包含了檔案路徑,即glob.glob括號內的路徑 而os.listdir只會獲取檔名。import glob file list glob.glob images 要列出所有內容路徑後面必須加 可以指定要遍歷的檔名格式 forfile in file list print f...

python資料夾操作

資料夾示意圖 提取路徑 size.py 提取相對路徑 import os print file 列印當前路徑 abspath os.getcwd 獲取當前路徑 ev os.path.abspath 獲取上一級目錄 rootpath os.path.abspath 獲取道根目錄的路徑 print ab...

python檔案和資料夾操作

python中對檔案 資料夾 檔案操作函式 的操作需要涉及到os模組和shutil模組。得到當前工作目錄,即當前python指令碼工作的目錄路徑 os.getcwd 返回指定目錄下的所有檔案和目錄名 os.listdir 函式用來刪除乙個檔案 os.remove 刪除多個目錄 os.removedi...