你應該知道的 10 個 Python 檔案系統方法


在編碼過程中,與檔案組織協作是一項例行工作,而 Python 提供了豐富的工具來與檔案和資料夾互動。在本討論中,我們將介紹十個您應該理解的 Python 檔案管理函式,以簡化您的編碼工作。我們將引導您逐步瞭解每個函式,並用簡單的步驟說明其操作。

建立和關閉檔案

假設 example.txt 包含文字“Hello, World!”。

示例

doc = open('example.txt', 'r')
contents = doc.read()
doc.close()
print(contents) 

輸出

Hello, World!

open() 操作接受兩個引數:檔案路徑和檔案模式。在本例中,模式為 'r',表示檔案被開啟以進行讀取。在完成使用檔案後,不要忘記使用 close() 方法關閉檔案。

讀取檔案

要讀取檔案的全部內容,請對檔案物件使用 read() 方法 -

示例

with open('example.txt', 'r') as doc:
   substance = doc.read()
print(substance)

輸出

Hello, World!

with 語句確保在退出程式碼塊時自動關閉檔案。content 變數將包含檔案的內容(字串形式)。

寫入檔案

要將資料寫入檔案,請以寫入模式 ('w') 開啟檔案並使用 write() 方法 -

示例

with open('output.txt', 'w') as doc:
doc.write('Hello, World!')

輸出

Hello, World!

此程式碼段建立一個名為 output.txt 的新檔案(如果已存在則覆蓋),並將字串 'Hello, World!' 寫入其中。

追加到檔案

要將資料追加到現有檔案,請以追加模式 ('a') 開啟檔案 -

示例

with open('example.txt', 'a') as doc:
doc.write('\nAppended text.')

輸出

Hello, World!

此程式碼片段開啟 example.txt 檔案,並將字串 '\nAppended text.' 追加到其中。

逐行讀取檔案

要逐行讀取檔案,請使用 for 迴圈迭代檔案物件 -

示例

with open('example.txt', 'r') as doc:
for row in doc:
print(row.strip())

輸出

Hello, World!

此程式碼段逐行讀取 example.txt 檔案,並列印每一行,不帶前導或尾隨空格。

建立資料夾

要建立新目錄,請使用 os.mkdir() 函式 -

示例

import os
os.mkdir('new_folder')

輸出

The directory "new_folder" was created successfully.

此程式碼段匯入 os 模組並建立一個名為 new_folder 的新資料夾。

刪除資料夾

要刪除空資料夾,請使用 os.rmdir() 函式 -

示例

import os
os.rmdir('empty_folder')

輸出

The directory "empty_folder" was removed successfully.

此程式碼段刪除 empty_folder。請注意,它僅在資料夾為空時有效。

列出檔案和資料夾

要列出目錄中的檔案和資料夾,請使用 os.listdir() 函式 -

示例

import os
docs_and_folders = os.listdir('some_folder')

輸出

['file1.txt', 'file2.txt', 'another_folder', 'yet_another_folder']

此程式碼段在 some_folder 中生成檔案和資料夾名稱列表。

檢查檔案或資料夾是否存在

要檢查檔案或資料夾是否存在,請使用 os.path.exists() 函式 -

示例

import os
if os.path.exists('example.txt'):
   print('The file exists')
else:
   print('The file does not exist')

輸出

The file exists

此程式碼段檢查 example.txt 檔案是否存在,並列印相應的語句。os.path.exists() 函式如果檔案或資料夾存在則返回 True,否則返回 False。

重新命名檔案或資料夾

要重新命名檔案或資料夾,請使用 os.rename() 函式 -

示例

import os
os.rename('old_designation.txt', 'new_designation.txt')
print(os.listdir())

此程式碼片段將檔案 old_designation.txt 重新命名為 new_designation.txt。它也可以用於將檔案或資料夾移動到新位置。

輸出

['new_designation.txt', 'another_file.txt', 'yet_another_file.txt']

結論

這十個 Python 檔案管理函式是與編碼專案中的檔案和資料夾互動的重要工具。透過熟悉這些函式並將它們整合到您的程式碼中,您可以節省時間並提高您的 Python 技能。不要猶豫,參考 Python 文件以獲取有關這些函式的更多資訊,並探索其他檔案組織功能。

更新於: 2023年8月9日

231 次瀏覽

開啟您的 職業生涯

透過完成課程獲得認證

開始
廣告

© . All rights reserved.