17 Python之資料夾與檔案路徑

2021-10-02 08:35:06 字數 2336 閱讀 2764

在作業系統處理檔案的觀念中會使用2個特殊符號....指的是當前資料夾,..指的是上一層資料夾。但是在使用上,當指當前資料夾時也可以省略.\

# -*- coding: utf-8 -*-

# @date: 2020/1/22 20:36

# @author: blueheart

# @blog:

import os

# 取得當前工作目錄 os.getcwd()

print

(os.getcwd())

# 取得絕對路徑 os.path.abspath

print

(os.path.abspath(

'.')

)# 列出目前工作目錄的絕對路徑

print

(os.path.abspath(

'..'))

# 列出上一層工作目錄的絕對路徑

print

(os.path.abspath(

'fileread.py'))

# 列出目前檔案的絕對路徑

# 傳回特定路段相對路徑os.path.relpath()

print

(os.path.relpath(

'c:\\'))

# 列出目前工作目錄到c:\相對目錄

print

(os.path.relpath(

'c:\\'

,'fileread.py'))

# 列出目前檔案到c:\的相對路徑

print

(os.path.relpath(

'c:\\users\blueheart\desktop'))

# 列出目前工作目錄到指定路徑相對目錄

'''c: 後面是兩個斜槓'''

import os

mydir =

'fileread'

# 如果mydir 資料夾不存在就建立此資料夾

if os.path.exists(mydir)

:print

("已經存在 %s"

% mydir)

else

: os.mkdir(mydir)

print

("建立 %s 資料夾成功"

% mydir)

import os

mydir =

'bbbb'

# 如果mydir資料夾存在就刪除

if os.path.exists(mydir)

: os.rmdir(mydir)

print

("刪除 %s 資料夾成功"

% mydir)

else

:print

("%s 資料夾不存在"

% mydir)

import os

myfile =

"test.py"

# 如果myfile檔案存在就刪除

if os.path.exists(myfile)

: os.remove(myfile)

print

("刪除 %s 檔案成功!"

% myfile)

else

:print

("%s 檔案不存在"

% myfile)

import os

newdir =

'c:\\users\blueheart\desktop\\檔案操作\python'

currentdir = os.getcwd(

)print

("當前工作資料夾是: %s"

% currentdir)

# 如果newdir不存在就建立此資料夾

if os.path.exists(newdir)

:print

("已經存在 %s"

% newdir)

else

: os.mkdir(newdir)

print

("建立 %s 資料夾成功!"

% newdir )

# 將目標資料夾改至newdir

os.chdir(newdir)

print

("最新工作夾"

, os.getcwd())

# 將目標資料夾改到當前檔案(fileread.py)所在資料夾

os.chdir(currentdir)

print

("當前資料夾"

, currentdir)

Python檔案與資料夾操作

import os import shutil if name main print os.path.abspath print os.path.split d pypro h.py print os.path.splitext d pypro h.py if not os.path.exists ...

Python 刪除檔案與資料夾

要刪除乙個檔案,需匯入os模組,使用其中的os.remove 函式 示例 刪除檔案 test.txt import os os.remove test.txt 為了避免出錯,需要在刪除之前檢查檔案是否存在 示例 刪除前檢查檔案是否存在 import os if os.path.exists test...

檔案與資料夾

建立資料夾 nsstring imagedir nsstring stringwithformat caches nshomedirectory dirname bool isdir no nsfilemanager filemanager nsfilemanager defaultmanager ...