深入理解 Python 操作系統(tǒng)的 14 個 API
大家好!今天我們要聊的是Python中的操作系統(tǒng)模塊——os。這個模塊提供了很多有用的函數(shù),幫助我們更好地與操作系統(tǒng)交互。無論是文件操作還是進程管理,os模塊都能提供強大的支持。本文將帶你一步步了解并掌握14個常用的os模塊API。
1.os.name
首先,讓我們看看os.name。這個屬性會返回當(dāng)前運行Python腳本的操作系統(tǒng)名稱。這對于編寫跨平臺的代碼非常有用,因為你可以通過它來判斷用戶正在使用哪種操作系統(tǒng)。
代碼示例:
import os
print("當(dāng)前操作系統(tǒng)名稱:", os.name)
輸出:如果你在Windows上運行這段代碼,輸出將是 "nt";而在Linux或Mac OS上則是 "posix"。
2.os.getcwd()
接下來是os.getcwd(),它用來獲取當(dāng)前工作目錄的路徑。這對于處理文件路徑特別有幫助。
代碼示例:
import os
print("當(dāng)前工作目錄:", os.getcwd())
輸出:例如,假設(shè)你的腳本位于C:\Users\YourName\Documents目錄下,那么輸出將會是這個路徑。
3.os.chdir(path)
os.chdir(path)可以改變當(dāng)前的工作目錄到指定路徑。這對于需要在不同目錄間切換的腳本來說非常實用。
代碼示例:
import os
# 改變到新的工作目錄
os.chdir('C:\\temp')
print("新工作目錄:", os.getcwd())
輸出:如果C:\temp存在,那么輸出就是該路徑。
4.os.listdir(path='.')
os.listdir(path='.')返回指定目錄下的所有文件和目錄名。默認(rèn)參數(shù)'.'表示當(dāng)前目錄。
代碼示例:
import os
files = os.listdir('.')
for f in files:
print(f)
輸出:這會列出當(dāng)前目錄下的所有文件和子目錄。
5.os.mkdir(path)
os.mkdir(path)用于創(chuàng)建一個新目錄。這是一個非常基礎(chǔ)但重要的功能。
代碼示例:
import os
# 創(chuàng)建新目錄
os.mkdir('new_directory')
print("新目錄已創(chuàng)建")
輸出:你會看到命令行提示“新目錄已創(chuàng)建”,同時在你的工作目錄中會出現(xiàn)一個名為new_directory的新目錄。
6.os.makedirs(path)
os.makedirs(path)類似于os.mkdir(),但它可以創(chuàng)建多級目錄。
代碼示例:
import os
# 創(chuàng)建多級目錄
os.makedirs('parent/child/subchild')
print("多級目錄已創(chuàng)建")
輸出:即使parent和child不存在,上述代碼也會創(chuàng)建完整的路徑。
7.os.rmdir(path)
os.rmdir(path)用來刪除空目錄。記住,只有當(dāng)目錄為空時,這個函數(shù)才能成功執(zhí)行。
代碼示例:
import os
# 刪除空目錄
os.rmdir('new_directory')
print("目錄已刪除")
輸出:如果new_directory是空的,那么它會被刪除,并打印出相應(yīng)的信息。
8.os.remove(path)
os.remove(path)用于刪除指定路徑下的文件。這是一個危險的操作,請務(wù)必小心使用!
代碼示例:
import os
# 刪除文件
os.remove('test.txt')
print("文件已刪除")
輸出:如果test.txt存在,那么它會被刪除,并顯示刪除成功的信息。
9.os.path.exists(path)
os.path.exists(path) 用于檢查指定路徑是否存在。這是非常常用的一個功能,特別是在處理文件和目錄時。
代碼示例:
import os
path = 'example.txt'
if os.path.exists(path):
print(f"{path} 存在")
else:
print(f"{path} 不存在")
輸出:如果 example.txt 文件存在,則輸出 “example.txt 存在”;否則輸出 “example.txt 不存在”。
10.os.path.isdir(path)
os.path.isdir(path) 用于檢查指定路徑是否為目錄。這在處理文件系統(tǒng)時非常有用。
代碼示例:
import os
path = 'example_directory'
if os.path.isdir(path):
print(f"{path} 是目錄")
else:
print(f"{path} 不是目錄")
輸出:如果 example_directory 存在并且是一個目錄,則輸出 “example_directory 是目錄”;否則輸出 “example_directory 不是目錄”。
11.os.path.isfile(path)
os.path.isfile(path) 用于檢查指定路徑是否為文件。與 os.path.isdir() 類似,這也是一個非常基礎(chǔ)且常用的功能。
代碼示例:
import os
path = 'example.txt'
if os.path.isfile(path):
print(f"{path} 是文件")
else:
print(f"{path} 不是文件")
輸出:如果 example.txt 存在并且是一個文件,則輸出 “example.txt 是文件”;否則輸出 “example.txt 不是文件”。
12.os.path.getsize(path)
os.path.getsize(path) 返回指定文件的大小(以字節(jié)為單位)。這對于獲取文件占用的空間非常有用。
代碼示例:
import os
path = 'example.txt'
if os.path.isfile(path):
size = os.path.getsize(path)
print(f"{path} 的大小為 {size} 字節(jié)")
else:
print(f"{path} 不存在或不是文件")
輸出:如果 example.txt 存在并且是一個文件,則輸出其大小;否則輸出相應(yīng)的錯誤信息。
13.os.rename(src, dst)
os.rename(src, dst) 用于重命名文件或移動文件/目錄。這是一個非常實用的功能,尤其是在處理大量文件時。
代碼示例:
import os
src = 'old_name.txt'
dst = 'new_name.txt'
if os.path.exists(src):
os.rename(src, dst)
print(f"{src} 已重命名為 {dst}")
else:
print(f"{src} 不存在")
輸出:如果 old_name.txt 存在,則將其重命名為 new_name.txt 并輸出相關(guān)信息;否則輸出錯誤信息。
14.os.walk(top, topdown=True, onerror=None, followlinks=False)
os.walk(top, topdown=True, onerror=None, followlinks=False) 是一個非常強大的函數(shù),用于遍歷目錄樹。它可以生成目錄樹中的文件名,在目錄樹中遞歸地進行遍歷。
代碼示例:
import os
top = 'example_directory'
for root, dirs, files in os.walk(top):
print(f"目錄: {root}")
for dir in dirs:
print(f" 子目錄: {os.path.join(root, dir)}")
for file in files:
print(f" 文件: {os.path.join(root, file)}")
輸出:這段代碼會遍歷 example_directory 及其子目錄,并打印出所有的子目錄和文件路徑。
實戰(zhàn)案例:備份文件夾
現(xiàn)在,讓我們通過一個實際的場景來綜合運用這些API。假設(shè)你需要備份某個目錄及其所有子目錄和文件。我們可以使用 os 模塊來實現(xiàn)這個功能。
代碼示例:
import os
import shutil
def backup_directory(source_dir, backup_dir):
if not os.path.exists(backup_dir):
os.makedirs(backup_dir)
for root, dirs, files in os.walk(source_dir):
relative_path = os.path.relpath(root, source_dir)
target_path = os.path.join(backup_dir, relative_path)
if not os.path.exists(target_path):
os.makedirs(target_path)
for file in files:
source_file = os.path.join(root, file)
backup_file = os.path.join(target_path, file)
shutil.copy2(source_file, backup_file)
source_directory = 'example_directory'
backup_directory = 'backup_directory'
backup_directory(source_directory, backup_directory)
print(f"{source_directory} 已備份到 {backup_directory}")
輸出:這段代碼會將 example_directory 及其所有子目錄和文件備份到 backup_directory 中,并輸出相應(yīng)的信息。
總結(jié)
本文詳細(xì)介紹了os模塊中的14個常用API,包括了文件和目錄的基本操作、路徑檢查以及目錄樹的遍歷等功能。通過這些API,我們可以更方便地處理各種文件系統(tǒng)相關(guān)的任務(wù)。希望這些知識能夠幫助你更加高效地使用Python進行開發(fā)。