首頁  >  文章  >  後端開發  >  解析 CSV 檔案時如何解決「FileNotFoundError:沒有這樣的檔案或目錄」?

解析 CSV 檔案時如何解決「FileNotFoundError:沒有這樣的檔案或目錄」?

Linda Hamilton
Linda Hamilton原創
2024-10-17 16:15:03355瀏覽

How to Resolve

無法找到CSV 檔案:「FileNotFoundError: [Errno 2] No Such File or Directory [Duplicate]」

嘗試解析 時碼時,開發者可能會遇到「FileNotFoundError: [Errno 2] No Such File or Directory」異常,表示Python 無法定位指定的檔案。

要解決這個問題,理解以下概念至關重要:相對和絕對路徑。當使用相對路徑開啟檔案時,例如給定程式碼中的“address.csv”,Python 假定該檔案位於目前工作目錄中。

要驗證目前工作目錄,請新增以下程式碼片段到您的程式碼:

<code class="python">import os
cwd = os.getcwd()  # Get the current working directory (cwd)
files = os.listdir(cwd)  # Get all the files in that directory
print("Files in %r: %s" % (cwd, files))</code>

或者,您可以使用絕對路徑指定檔案的確切位置,例如:

<code class="python">f = open("/Users/foo/address.csv")  # Replace with the full path to the CSV file</code>

透過使用絕對路徑,您明確指示Python 在哪裡找到文件,避免了基於當前工作目錄的假設。

以上是解析 CSV 檔案時如何解決「FileNotFoundError:沒有這樣的檔案或目錄」?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn