3 檔案讀寫
4 資料夾操作**
python中檔案和資料夾操作還是十分重要的~
首先可以檢視一下工作目錄,
# 檢視當前的工作目錄
print
(os.getcwd(
))
如果工作目錄不正確,可以用os.chdir()函式來進行修改;
os.path.dirname(__file__)
os.chdir(os.path.dirname(__file__)
)
# 遍歷當前資料夾的直接子檔案
for root, dirs, files in os.walk(path)
:for
file
in files:
# 獲取檔案所屬目錄
print
(root)
# 獲取檔案路徑
print
(os.path.join(root,
file
))
使用函式os.path.splitext()獲取file字串的副檔名;
其實我之前先看到的是os.path.split()
函式,
關於os.path.split()
的解釋,我們可以看看python的官方文件:
而os.path.basename()
其實就是返回os.path.split()
的第二個返回值,所以直接使用os.path.basename()
就可以了;
os.path.basename(path)
在將多行列表資料寫入.txt
檔案時,使用f.writelines()
函式,因為f.writelines()
函式會比f.write()
函式效率更高一些;
可以參考下面的示例**
# 以json格式寫入檔案
with
open
(json_file,
"w")
as f:
json.dump(data, f)
# 建立資料夾
os.mkdir(folder)
if os.path.isdir(
dir)
: shutil.rmtree(
dir)
# 建立資料夾
assert os.path.isdir(
"path/folder"
)
# 遍歷當前資料夾的直接子檔案
forfile
in os.listdir(root)
:print
(file
)
python檔案和資料夾操作
python中對檔案 資料夾 檔案操作函式 的操作需要涉及到os模組和shutil模組。得到當前工作目錄,即當前python指令碼工作的目錄路徑 os.getcwd 返回指定目錄下的所有檔案和目錄名 os.listdir 函式用來刪除乙個檔案 os.remove 刪除多個目錄 os.removedi...
Linux中檔案和資料夾操作命令
1 cd 進入根目錄 change directory cd 返回上一層目錄,2 ls 檢視當前目錄內容,顯示目錄清單 3 pwd 顯示當前目錄路徑 4 ls dl 可以當前檔案屬性 ls l 顯示所有檔案屬性 例子如下 5 關於檔案屬性 從左到右箭頭的解釋如下 d在此處代表檔案的型別,檔案的型別有...
Perl 檔案和資料夾操作
作為一門程式語言,perl有著強大的檔案和資料夾操作功能。perl利用檔案控制代碼 file handle 和資料夾控制代碼 dir handle 與作業系統進行輸入輸出連線。檔案和資料夾控制代碼一般使用大寫子母或指定標量以示特殊。檔案開啟語句及說明 一般加入die函式做開啟失敗的提示。my fil...