Python 的檔案和目錄操作在日常開發中扮演著重要的角色。除了基本的 os 模組,shutil、glob 以及 datetime 和 time 模組提供了更強大的功能,讓檔案管理更加便捷和高效。這些模組的應用場景廣泛,從簡單的檔案複製、移動到複雜的目錄遍歷、時間戳記處理,都能輕鬆應對。熟練掌握這些工具,能有效提升開發效率,簡化程式碼,並更好地管理檔案系統。對於需要處理大量檔案或進行複雜檔案操作的專案來說,這些模組更是不可或缺的利器。
Python 中的 UserList、UserString 與 Itertools:玄貓的客製化資料結構與無限序列生成之道
Python 提供了豐富的內建模組,讓開發者能更有效率地處理各種資料結構與序列。collections 模組中的 UserList 和 UserString,以及 itertools 模組中的 count、cycle 和 repeat,都是相當實用的工具。身為一位熱愛 Python 的技術專家,玄貓將分享如何運用這些模組,開發更具彈性的程式碼。
開發客製化 List:UserList 的妙用
Python 內建的 list 雖然功能強大,但有時我們需要更客製化的行為。這時,UserList 就派上用場了。UserList 是一個可以繼承的類別,讓我們能修改 list 的預設行為。
例項:讓 List 自動計算總和
假設我們需要一個 list,每次呼叫 sum() 方法時,都能自動計算 list 中所有元素的總和。以下是如何使用 UserList 實作這個功能:
from collections import UserList
class MyList(UserList):
def sum(self):
return sum(self.data)
# 示範
l = MyList([1, 2, 3, 4])
print(l.sum()) # 輸出:10
內容解密
- 首先,我們從
collections模組匯入UserList。 - 接著,我們定義一個名為
MyList的新類別,並繼承UserList。 - 在
MyList類別中,我們定義了一個sum()方法,該方法使用內建的sum()函式來計算self.data(也就是 list 內容) 的總和。
擴充套件功能:支援負索引的 List
另一個常見的需求是讓 list 支援負索引,也就是可以使用 l[-1] 來取得最後一個元素。以下是如何修改 __getitem__ 方法來實作這個功能:
from collections import UserList
class MyList(UserList):
def sum(self):
return sum(self.data)
def __getitem__(self, index):
if index >= 0:
return self.data[index]
else:
return self.data[len(self.data) + index]
# 示範
l = MyList([1, 2, 3, 4])
print(l[0]) # 輸出:1
print(l[-1]) # 輸出:4
內容解密
- 我們覆寫了
__getitem__方法,這個方法負責處理 list 的索引操作。 - 如果索引值大於等於 0,我們就直接回傳該索引位置的元素。
- 如果索引值小於 0,我們就將索引值加上 list 的長度,以取得對應的正索引值,然後回傳該位置的元素。
客製化字串:UserString 的應用
類別似於 UserList,UserString 讓我們能客製化字串的行為。
例項:自動轉換為大寫的字串
以下是如何建立一個 UserString 子類別,讓字串永遠以大寫形式呈現:
from collections import UserString
class UppercaseString(UserString):
def __str__(self):
return self.data.upper()
# 示範
my_string = UppercaseString("Hello, World!")
print(my_string) # 輸出:HELLO, WORLD!
內容解密
- 我們定義了一個名為
UppercaseString的新類別,並繼承UserString。 - 我們覆寫了
__str__方法,這個方法負責定義當物件被轉換為字串時的行為。 - 在
__str__方法中,我們使用self.data.upper()將字串轉換為大寫,然後回傳。
移除前後空白的字串
以下是如何建立一個 UserString 子類別,自動移除字串前後的空白:
from collections import UserString
class StrippedString(UserString):
def __str__(self):
return self.data.strip()
# 示範
my_string = StrippedString(" Hello, World! ")
print(my_string) # 輸出:Hello, World!
內容解密
- 我們定義了一個名為
StrippedString的新類別,並繼承UserString。 - 我們覆寫了
__str__方法,並使用self.data.strip()移除字串前後的空白。
無限序列的奧秘:Itertools 的 count、cycle 和 repeat
itertools 模組提供了一系列用於處理迭代器的函式,其中 count、cycle 和 repeat 特別適合用於產生無限或有限的序列。
count:生成無限數字序列
count 函式可以從指定的起始值開始,以指定的間隔生成一個無限的數字序列。
from itertools import count
for i in count(start=1, step=2):
if i > 10:
break
print(i) # 輸出:1 3 5 7 9
內容解密
count(start=1, step=2)會從 1 開始,每次增加 2,生成一個無限序列。- 我們使用
for迴圈來迭代這個序列,並在數字大於 10 時停止。
Python Itertools:無限序列的生成藝術
Python 的 itertools 模組是個寶藏,尤其在處理迭代器時。它提供了一系列高效、節省記憶體的工具,讓我們能以優雅的方式操作序列。今天,玄貓就來談談如何使用 itertools 中的 count、cycle 和 repeat 函式,輕鬆生成無限或有限序列。
count 函式:無盡的數字流
count 函式能建立一個無限的數字序列,從指定的起始值開始,按指定的步長遞增。這在需要生成連續數字時非常有用。
from itertools import count
# 從 1 開始,每次遞增 2
number_generator = count(1, 2)
# 迭代前 5 個數字
for i in range(5):
print(next(number_generator))
# 輸出:
# 1
# 3
# 5
# 7
# 9
內容解密
- 首先,我們從
itertools匯入count函式。 - 然後,我們使用
count(1, 2)建立一個從 1 開始,每次遞增 2 的無限序列。 - 接著,我們使用一個
for迴圈來迭代這個序列的前 5 個數字,並將它們印出來。
玄貓認為,count 函式在需要生成唯一 ID 或時間序列時特別有用。
cycle 函式:迴圈往復的美妙
cycle 函式能將一個可迭代物件變成一個無限迴圈的序列。這在需要重複使用一組值時非常方便。
from itertools import cycle
colors = ['red', 'green', 'blue']
color_cycle = cycle(colors)
for i in range(6):
print(next(color_cycle))
# 輸出:
# red
# green
# blue
# red
# green
# blue
內容解密
- 首先,我們從
itertools匯入cycle函式。 - 然後,我們建立一個顏色列表
colors。 - 接著,我們使用
cycle(colors)建立一個無限迴圈的顏色序列。 - 最後,我們使用一個
for迴圈來迭代這個序列的前 6 個元素,並將它們印出來。
玄貓發現,cycle 函式在處理輪播圖或需要重複播放列表時非常實用。
repeat 函式:單調的重複之歌
repeat 函式能生成一個由相同值重複組成的序列,可以指定重複次數,也可以無限重複。
from itertools import repeat
for i in repeat(10, 5):
print(i)
# 輸出:
# 10
# 10
# 10
# 10
# 10
內容解密
- 首先,我們從
itertools匯入repeat函式。 - 然後,我們使用
repeat(10, 5)建立一個重複 5 次數字 10 的序列。 - 最後,我們使用一個
for迴圈來迭代這個序列,並將每個元素印出來。
玄貓認為,repeat 函式在初始化資料或填充預設值時非常有用。
連結、複製與平行:itertools 的進階應用
除了生成無限序列,itertools 還提供了一些強大的工具來操作和組合迭代器。玄貓將介紹 chain、tee 和 zip_longest 這三個函式,它們能幫助你更有效地處理迭代器。
chain 函式:串聯多個迭代器
chain 函式能將多個迭代器串聯成一個單一的迭代器。這在需要合併多個來源的資料時非常方便。
from itertools import chain
list_a = [1, 2, 3]
list_b = ['a', 'b', 'c']
combined = chain(list_a, list_b)
for item in combined:
print(item)
# 輸出:
# 1
# 2
# 3
# a
# b
# c
內容解密
- 首先,我們從
itertools匯入chain函式。 - 然後,我們建立兩個列表
list_a和list_b。 - 接著,我們使用
chain(list_a, list_b)將這兩個列表串聯成一個迭代器。 - 最後,我們使用一個
for迴圈來迭代這個組合後的迭代器,並印出每個元素。
玄貓發現,chain 函式在合併多個日誌檔案或資料函式庫查詢結果時非常有用。
tee 函式:複製迭代器
tee 函式能從一個迭代器建立多個獨立的迭代器。這在需要多次迭代同一個資料來源時非常有用。
from itertools import tee
numbers = [1, 2, 3, 4, 5]
iter1, iter2 = tee(numbers, 2)
print(list(iter1))
print(list(iter2))
# 輸出:
# [1, 2, 3, 4, 5]
# [1, 2, 3, 4, 5]
內容解密
- 首先,我們從
itertools匯入tee函式。 - 然後,我們建立一個數字列表
numbers。 - 接著,我們使用
tee(numbers, 2)從這個列表建立兩個獨立的迭代器iter1和iter2。 - 最後,我們將這兩個迭代器轉換為列表並印出。
玄貓認為,tee 函式在需要對同一個資料來源進行多次分析或處理時非常有用。
zip_longest 函式:處理長度不一的迭代器
zip_longest 函式能將多個迭代器合併成一個迭代器,即使這些迭代器的長度不一致。它會用指定的預設值填充較短的迭代器,直到所有迭代器都耗盡。
from itertools import zip_longest
names = ['Alice', 'Bob', 'Charlie']
ages = [25, 30]
combined = zip_longest(names, ages, fillvalue='Unknown')
for item in combined:
print(item)
# 輸出:
# ('Alice', 25)
# ('Bob', 30)
# ('Charlie', 'Unknown')
內容解密
- 首先,我們從
itertools匯入zip_longest函式。 - 然後,我們建立兩個列表
names和ages,它們的長度不一致。 - 接著,我們使用
zip_longest(names, ages, fillvalue='Unknown')將這兩個列表合併成一個迭代器,並使用'Unknown'作為預設值填充較短的列表。 - 最後,我們使用一個
for迴圈來迭代這個組合後的迭代器,並印出每個元素。
玄貓發現,zip_longest 函式在處理來自不同來源的資料,與這些資料的完整性不一致時非常有用。
精準切割與條件篩選:itertools 的高階迭代技巧
itertools 模組不僅僅提供簡單的迭代工具,還包含一些更高階的函式,可以幫助我們精準地控制迭代過程。玄貓將介紹 islice、dropwhile 和 takewhile 這三個函式,它們能讓你以更精細的方式操作迭代器。
islice 函式:精確的切片操作
islice 函式允許你對迭代器進行切片操作,就像對列表進行切片一樣,但它不會建立新的列表,而是傳回一個迭代器,從而節省記憶體。
from itertools import islice
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
sliced = islice(numbers, 2, 7, 2) # 從索引 2 開始,到 7 結束,步長為 2
for item in sliced:
print(item)
# 輸出:
# 3
# 5
# 7
內容解密
- 首先,我們從
itertools匯入islice函式。 - 然後,我們建立一個數字列表
numbers。 - 接著,我們使用
islice(numbers, 2, 7, 2)對這個列表進行切片,從索引 2 開始,到 7 結束(不包含 7),步長為 2。 - 最後,我們使用一個
for迴圈來迭代這個切片後的迭代器,並印出每個元素。
玄貓認為,islice 函式在處理大型資料集時非常有用,因為它可以避免一次性將所有資料載入記憶體。
dropwhile 函式:條件捨棄
dropwhile 函式會從迭代器中捨棄元素,直到遇到第一個不符合條件的元素為止,然後傳回剩餘的所有元素。
from itertools import dropwhile
numbers = [1, 2, 3, 4, 5, 1, 2, 3]
filtered = dropwhile(lambda x: x < 4, numbers) # 捨棄小於 4 的元素
for item in filtered:
print(item)
# 輸出:
# 4
# 5
# 1
# 2
# 3
內容解密
- 首先,我們從
itertools匯入dropwhile函式。 - 然後,我們建立一個數字列表
numbers。 - 接著,我們使用
dropwhile(lambda x: x < 4, numbers)捨棄列表中小於 4 的元素,直到遇到第一個不小於 4 的元素為止。 - 最後,我們使用一個
for迴圈來迭代這個過濾後的迭代器,並印出每個元素。
玄貓發現,dropwhile 函式在處理需要跳過前導無效資料的資料流時非常有用。
takewhile 函式:條件選取
takewhile 函式會從迭代器中選取元素,直到遇到第一個不符合條件的元素為止,然後停止選取。
from itertools import takewhile
numbers = [1, 2, 3, 4, 5, 1, 2, 3]
selected = takewhile(lambda x: x < 4, numbers) # 選取小於 4 的元素
for item in selected:
print(item)
# 輸出:
# 1
# 2
# 3
內容解密
- 首先,我們從
itertools匯入takewhile函式。 - 然後,我們建立一個數字列表
numbers。 - 接著,我們使用
takewhile(lambda x: x < 4, numbers)選取列表中小於 4 的元素,直到遇到第一個不小於 4 的元素為止。 - 最後,我們使用一個
for迴圈來迭代這個選取後的迭代器,並印出每個元素。
玄貓認為,takewhile 函式在處理需要從資料流中提取有效資料,直到遇到終止條件為止的情況時非常有用。
總之,itertools 模組是 Python 中一個非常強大的工具,它提供了許多高效、節省記憶體的函式,可以幫助我們輕鬆地操作迭代器。無論是生成無限序列,還是對迭代器進行切片、過濾和組合,itertools 都能提供簡潔而優雅的解決方案。
使用 itertools 模組提升 Python 效率:玄貓的實戰經驗分享
在資料處理和演算法開發中,效率至關重要。Python 的 itertools 模組提供了一系列高效的迭代器工具,可以簡化程式碼並提升效能。身為玄貓,我將分享一些在實際專案中使用 itertools 的經驗,希望能幫助大家更好地理解和應用這個強大的模組。
takewhile():玄貓如何利用它最佳化資料流處理
takewhile() 函式允許我們從一個可迭代物件中提取元素,直到某個條件不再滿足。這在處理無限資料流或需要根據特定條件截斷資料時非常有用。
語法:
from itertools import takewhile
takewhile(predicate, iterable)
predicate 是一個函式,它接受可迭代物件的元素作為引數,並傳回一個布林值,指示是否應提取該元素。iterable 是要迭代的可迭代物件。
範例:
假設我們有一個數字列表,想要提取所有小於 5 的數字:
my_list = [1, 3, 5, 7, 2, 4, 6]
print(list(takewhile(lambda x: x < 5, my_list)))
# 輸出: [1, 3]
玄貓在使用 takewhile() 時,發現它在處理日誌資料時特別有效。例如,我們可以從日誌檔案中提取所有在特定時間之前的事件,而無需讀取整個檔案。
groupby():玄貓如何用它進行高效的資料分組
groupby() 函式可以根據指定的鍵函式將可迭代物件中的專案分組。這在資料分析和資料操作中非常有用,可以根據某些標準對資料進行分類別。
語法:
from itertools import groupby
groupby(iterable, key=None)
iterable 是要分組的可迭代物件,key 是一個可選的函式,它接受可迭代物件的元素作為引數,並傳回該元素的鍵值。如果未提供鍵函式,則元素本身將用作鍵。
範例:
假設我們有一個單詞列表,想要根據它們的首字母進行分組:
words = ['apple', 'banana', 'cherry', 'date', 'elderberry', 'fig']
groups = groupby(words, key=lambda x: x[0])
for key, group in groups:
print(key, list(group))
# 輸出:
# a ['apple']
# b ['banana']
# c ['cherry']
# d ['date']
# e ['elderberry']
# f ['fig']
玄貓在處理客戶資料時,經常使用 groupby() 根據客戶的地理位置或購買歷史對客戶進行分組,以便進行更精確的行銷活動。
另一個範例,根據數字的奇偶性進行分組:
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
groups = groupby(numbers, key=lambda x: 'even' if x % 2 == 0 else 'odd')
for key, group in groups:
print(key, list(group))
# 輸出:
# odd [1]
# even [2, 4, 6, 8, 10]
# odd [3, 5, 7, 9]
starmap() 和 product():玄貓如何用它們簡化複雜的計算
starmap() 函式接受一個函式和一個元組的可迭代物件作為引數。它將函式應用於可迭代物件中的每個元組,並將元組的元素解封裝為函式的引數。product() 函式接受兩個或多個可迭代物件作為引數,並傳回一個迭代器,該迭代器生成包含來自輸入可迭代物件的元素的所有可能組合的元組。
語法:
from itertools import starmap, product
starmap(function, iterable)
product(*iterables)
範例:
計算元組列表中數字的平方和:
from itertools import starmap
numbers = [(1, 2), (3, 4), (5, 6)]
squares = starmap(lambda x, y: x**2 + y**2, numbers)
for square in squares:
print(square)
# 輸出:
# 5
# 25
# 61
生成兩個列表的所有可能組合:
from itertools import product
list1 = ['A', 'B']
list2 = [1, 2, 3]
combinations = product(list1, list2)
for combination in combinations:
print(combination)
# 輸出:
# ('A', 1)
# ('A', 2)
# ('A', 3)
# ('B', 1)
# ('B', 2)
# ('B', 3)
玄貓在進行機器學習模型的超引數調整時,經常使用 product() 生成所有可能的超參陣列合,然後使用 starmap() 平行評估每個組合的效能。
使用 os 和 os.path 模組進行檔案和目錄存取:玄貓的檔案管理技巧
os 和 os.path 模組提供了廣泛的函式,用於存取檔案系統上的檔案和目錄。這些模組可用於執行各種操作,例如導航目錄、建立和刪除檔案、檢查檔案屬性等等。
導航目錄:
import os
# 取得當前工作目錄
current_dir = os.getcwd()
print(f"當前目錄: {current_dir}")
# 切換到另一個目錄
os.chdir('/path/to/your/directory')
print(f"切換後目錄: {os.getcwd()}")
# 列出目錄中的所有檔案和目錄
files = os.listdir(current_dir)
print(f"目錄中的檔案: {files}")
玄貓在處理大量資料集時,經常使用 os 和 os.path 模組來自動化檔案管理任務,例如批次重新命名檔案、移動檔案到不同的目錄,以及建立資料夾結構。
總之,itertools 模組和 os 模組是 Python 中非常強大的工具,可以幫助我們更有效率地處理資料和管理檔案。希望這些玄貓的實戰經驗分享能幫助大家更好地利用這些工具,提升程式碼的效能和可讀性。
```tool_code
# 程式碼計數器初始化
標記移除計數器 = {
"START_DOCUMENT": 0,
"CONTINUE_DOCUMENT": 0,
"END_DOCUMENT": 0
}
# 定義標記移除函式
def 移除標記(文字):
global 標記移除計數器
import re
文字, count1 = re.subn(r"", "", 文字)
文字, count2 = re.subn(r"", "", 文字)
文字, count3 = re.subn(r"", "", 文字)
標記移除計數器["START_DOCUMENT"] += count1
標記移除計數器["CONTINUE_DOCUMENT"] += count2
標記移除計數器["END_DOCUMENT"] += count3
return 文字
# 移除標記
文字 = """
The os module provides functions for navigating directories such as
chdir() to change the current working directory, listdir() to list the
contents of a directory, and mkdir() to create a new directory. Here's
an example:
import os
# get current working directory
print(os.getcwd())
# change working directory
os.chdir('/path/to/directory')
# list directory contents
print(os.listdir())
# create new directory
os.mkdir('new_directory')
File Properties:
The os.path module provides functions for working with file properties
such as exists() to check if a file or directory exists, getsize() to get
the size of a file, and isdir() to check if a given path is a directory.
Here's an example:
import os
# check if file exists
if os.path.exists('file.txt'):
print('file exists')
# get file size
print(os.path.getsize('file.txt'))
# check if path is a directory
if os.path.isdir('/path/to/directory'):
print('path is a directory')
File Operations:
The os module provides functions for performing file operations such
as remove() to delete a file, rename() to rename a file, and stat() to
get detailed information about a file. Here's an example:
import os
# delete file
os.remove('file.txt')
# rename file
os.rename('old_file.txt', 'new_file.txt')
# get file stats
stat_info = os.stat('file.txt')
print(stat_info.st_size)
Walking Directories:
The os module provides the walk() function, which can be used to
traverse a directory tree and perform operations on files and
directories. Here's an example:
import os
# traverse directory tree
for dirpath, dirnames, filenames in
os.walk('/path/to/directory'):
print('Current directory: {}'.format(dirpath))
print('Directories: {}'.format(dirnames))
print('Files: {}'.format(filenames))
These are just a few examples of the many functions provided by the
os and os.path modules for file and directory access. By utilizing
these modules, you can perform various operations on files and
directories in a convenient and efficient manner.
Using pathlib
Python's pathlib module provides an object-oriented interface to
access files and directories. It is part of the standard library and
offers a more intuitive way to work with file and directory paths
compared to the os and os.path modules.
Here are some examples of how to use the pathlib module for file and
directory access:
Creating Paths:
The pathlib.Path() function can be used to create a path object
representing a file or directory path. Here's an example:
from pathlib import Path
# create a path object representing a file
file_path = Path('/path/to/file.txt')
# create a path object representing a
directory
dir_path = Path('/path/to/directory')
Checking Path Properties:
The pathlib.Path() object provides a number of useful methods for
checking the properties of a file or directory path such as exists() to
check if a path exists, is_file() to check if a path is a file, and is_dir()
to check if a path is a directory. Here's an example:
from pathlib import Path
# check if path exists
file_path = Path('/path/to/file.txt')
if file_path.exists():
print('file exists')
# check if path is a file
if file_path.is_file():
print('path is a file')
# check if path is a directory
dir_path = Path('/path/to/directory')
if dir_path.is_dir():
print('path is a directory')
Creating Directories:
The pathlib.Path() object provides a mkdir() method that can be used
to create a new directory. Here's an example:
from pathlib import Path
# create a new directory
dir_path = Path('/path/to/new/directory')
dir_path.mkdir()
Listing Directory Contents:
The pathlib.Path() object provides a iterdir() method that can be used
to iterate over the contents of a directory. Here's an example:
from pathlib import Path
# list directory contents
dir_path = Path('/path/to/directory')
for item in dir_path.iterdir():
print(item)
Reading and Writing Files:
The pathlib.Path() object provides methods for reading and writing
files such as read_text() to read the contents of a text file,
write_text() to write text to a file, and read_bytes() and write_bytes()
for reading and writing binary files. Here's an example:
from pathlib import Path
# read contents of a file
file_path = Path('/path/to/file.txt')
contents = file_path.read_text()
print(contents)
# write text to a file
file_path.write_text('Hello, World!')
# read contents of a binary file
binary_file_path = Path('/path/to/binary/file')
binary_contents =
binary_file_path.read_bytes()
# write bytes to a binary file
binary_file_path.write_bytes(b'binary data')
These are just a few examples of the many functions and methods
provided by the pathlib module for file and directory access. By
utilizing this module, you can perform various operations on files and
directories in a more intuitive and object-oriented manner.
Using shutil
Python's shutil module provides a high-level interface for file and
directory operations. It is part of the standard library and can be used
to copy, move, or delete files and directories, as well as to archive
files.
Here are some examples of how to use the shutil module for file and
directory access:
Copying Files and Directories:
The shutil.copy() function can be used to copy a file, while the
shutil.copytree() function can be used to copy an entire directory tree.
Here's an example:
import shutil
# copy a file
src_file = '/path/to/source/file.txt'
dest_dir = '/path/to/destination'
shutil.copy(src_file, dest_dir)
# copy a directory tree
src_dir = '/path/to/source'
dest_dir = '/path/to/destination'
shutil.copytree(src_dir, dest_dir)
Moving and Renaming Files and Directories:
The shutil.move() function can be used to move or rename a file or
directory. Here's an example:
import shutil
# move a file
src_file = '/path/to/source/file.txt'
dest_dir = '/path/to/destination'
shutil.move(src_file, dest_dir)
# rename a file
src_file = '/path/to/source/old_name.txt'
dest_file = '/path/to/source/new_name.txt'
shutil.move(src_file, dest_file)
# move a directory
src_dir = '/path/to/source'
dest_dir = '/path/to/destination'
shutil.move(src_dir, dest_dir)
# rename a directory
src_dir = '/path/to/source/old_name'
dest_dir = '/path/to/source/new_name'
shutil.move(src_dir, dest_dir)
Removing Files and Directories:
The os.remove() function can be used to remove a file, while the
shutil.rmtree() function can be used to remove an entire directory
tree. Here's an example:
import os
import shutil
"""
文字 = 移除標記(文字)
# 輸出計數器
print(標記移除計數器)
print(文字)
Python檔案操作進階:shutil、glob 與時間模組的實戰應用
在Python的世界裡,檔案和目錄操作是日常開發中不可或缺的一環。除了內建的os模組,shutil、glob和datetime等模組更提供了強大的輔助功能,讓檔案管理變得輕鬆寫意。身為一個在金融科技業打滾多年的老手,玄貓將分享如何運用這些工具,讓你的Python程式在檔案處理上更加高效。
shutil模組:檔案操作的瑞士刀
shutil模組就像一把瑞士刀,提供了一系列高階檔案操作功能。無論是檔案複製、移動、刪除,還是壓縮、解壓縮,shutil都能搞定。
檔案與目錄的搬移與複製
在開發過程中,我們經常需要複製或移動檔案。shutil.copy()和shutil.move()就是你的好幫手。
import shutil
# 複製檔案
src_path = '/path/to/source/file.txt'
dst_path = '/path/to/destination/file.txt'
shutil.copy(src_path, dst_path)
# 移動檔案
src_path = '/path/to/source/file.txt'
dst_path = '/path/to/destination/file.txt'
shutil.move(src_path, dst_path)
玄貓提醒:shutil.copy()預設只複製檔案內容和許可權,若要複製所有metadata,可以使用shutil.copy2()。
目錄的移除
有時候,我們需要刪除整個目錄樹。shutil.rmtree()可以幫你遞迴刪除目錄及其所有內容。
import shutil
import os
# 移除目錄樹
dir_path = '/path/to/directory'
shutil.rmtree(dir_path)
# 移除檔案
file_path = '/path/to/file.txt'
os.remove(file_path)
檔案壓縮
shutil.make_archive()能將目錄壓縮成zip、tar等多種格式,方便檔案傳輸和備份。
import shutil
# 建立zip壓縮檔
src_dir = '/path/to/source'
archive_name = 'my_archive'
shutil.make_archive(archive_name, 'zip', src_dir)
glob模組:檔案搜尋的利器
當你需要根據特定模式尋找檔案時,glob模組就派上用場了。它使用Unix shell風格的萬用字元,讓你輕鬆找到目標檔案。
指定副檔名的檔案
import glob
# 尋找所有.txt檔案
dir_path = '/path/to/directory'
txt_files = glob.glob(f"{dir_path}/*.txt")
print(txt_files)
指設定檔名的檔案
import glob
# 尋找所有名為'file.txt'的檔案
dir_path = '/path/to/directory'
file_path = f"{dir_path}/file.txt"
matching_files = glob.glob(file_path)
print(matching_files)
尋找目錄
import glob
# 尋找所有目錄
dir_path = '/path/to/directory'
matching_dirs = glob.glob(f"{dir_path}/*/")
print(matching_dirs)
遞迴搜尋
glob還支援遞迴搜尋,讓你可以在目錄及其子目錄中尋找檔案。
import glob
# 遞迴尋找所有.txt檔案
dir_path = '/path/to/directory'
txt_files = glob.glob(f"{dir_path}/**/*.txt", recursive=True)
print(txt_files)
datetime模組:時間戳記的魔法師
在檔案管理中,時間戳記扮演著重要的角色。datetime模組讓你能夠輕鬆地讀取、轉換和格式化檔案的建立、修改和存取時間。
玄貓解密時間戳記
檔案的時間戳記是以秒為單位的浮點數,表示自 epoch (1970年1月1日 00:00:00 UTC) 以來的時間。
讀取時間戳記
import os
import datetime
file_path = '/path/to/file.txt'
# 取得建立時間
creation_time = os.path.getctime(file_path)
creation_time = datetime.datetime.fromtimestamp(creation_time)
print("Creation time:", creation_time)
# 取得修改時間
modification_time = os.path.getmtime(file_path)
modification_time = datetime.datetime.fromtimestamp(modification_time)
print("Modification time:", modification_time)
# 取得存取時間
access_time = os.path.getatime(file_path)
access_time = datetime.datetime.fromtimestamp(access_time)
print("Access time:", access_time)
格式化時間戳記
datetime模組提供strftime()方法,讓你將時間戳記轉換成各種易讀的格式。
import os
import datetime
file_path = '/path/to/file.txt'
# 取得修改時間
modification_time = os.path.getmtime(file_path)
modification_time = datetime.datetime.fromtimestamp(modification_time)
# 轉換成ISO格式
modification_time_str = modification_time.strftime("%Y-%m-%d %H:%M:%S")
print("Modification time:", modification_time_str)
# 轉換成自訂格式
modification_time_str = modification_time.strftime("%b %d, %Y %I:%M:%S %p")
print("Modification time:", modification_time_str)
time 模組:更底層的時間操作
time 模組提供了更底層的時間操作功能,雖然在檔案處理中不如 datetime 常用,但在某些特定場景下仍然很有用。
玄貓小提示:time vs datetime
time 模組主要處理時間相關的底層操作,例如時間的暫停 (sleep) 和時間的測量。datetime 則更專注於時間的表示和格式化。
讀取時間戳記
和 datetime 類別似,time 也可以讀取檔案的時間戳記,但通常需要搭配 os.path 模組使用。
import os
import time
file_path = '/path/to/file.txt'
# 取得建立時間
creation_time = os.path.getctime(file_path)
creation_time = time.ctime(creation_time)
print("Creation time:", creation_time)
# 取得修改時間
modification_time = os.path.getmtime(file_path)
modification_time = time.ctime(modification_time)
print("Modification time:", modification_time)
# 取得存取時間
access_time = os.path.getatime(file_path)
access_time = time.ctime(access_time)
print("Access time:", access_time)
time.ctime() 函式將時間戳記轉換為易讀的字串格式。