簡體   English   中英

Python讀寫文件時,如何在不同的操作系統上獲取相同的路徑?

[英]How to get the same path on different operating systems when reading and writing files in Python?

我正在和一個朋友一起做一個項目,我們使用不同的操作系統(Windows / MACOS),我們認為這是這個問題的根源。 問題是在讀取文件時,我們有不同的工作目錄,我的在層次結構中更深了一步。

我的路徑: C:/Code-projects/Python/python-laborations/lab1

而他的則是: C:/Code-projects/Python/python-laborations (不完全是因為他在 Mac 上,但這無關緊要)

我們想訪問路徑C:/Code-projects/Python/python-laborations/data 稍后我們也想寫入這個目錄。

現在,當嘗試讀取文件時,以下字符串對他'data/tramstops.json''data/tramstops.json'但我會收到 FileNotFound 錯誤。 相反,我需要使用路徑'../data/tramstops.json'並且一切正常。

我們對此的組合解決方案如下所示,其中路徑例如'data/tramstops.json'

try:
    with open(path, 'r', encoding="utf-8") as file:
        do_something()
except FileNotFoundError:
    with open('../' + path, 'r', encoding="utf-8") as file:
        do_something()

但是現在我們想寫入一個文件,使用這種方法不會引發異常,而只是創建文件(在錯誤的地方)。 所以我們需要一個不同的解決方案。 我們嘗試的一件事是使用 os 模塊構建絕對路徑。 偽代碼如下:

current_dir = os.getcwd()
split current_dir into list
if "lab1" in list then delete it
add path-argument to current_dir

這個解決方案有效,但它不是很優雅,我們覺得必須有更好的方法。 我們還希望避免將路徑硬編碼到我們的代碼中,因為我們不希望它依賴於文件結構。 有沒有更好的辦法?

操作系統路徑

Instead of importing this module directly, import os and refer to
this module as os.path.  The "os.path" name is an alias for this
module on Posix systems; on other systems (e.g. Mac, Windows),
os.path provides the same operations in a manner specific to that
platform, and is an alias to another module (e.g. macpath, ntpath).

Some of this can actually be useful on non-Posix systems too, e.g.
for manipulation of the pathname component of URLs.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM