簡體   English   中英

有沒有一種方法可以使用〜指向Python中文件路徑中的主目錄?

[英]Is there a way I can use ~ to point to the home directory in file paths in Python?

我試圖用Python(版本3.5,但我也對2.7很好奇)而不是Shell腳本來自動化一些任務。 如果我能寫"~/myfile.txt"而不是/home/me/myfile.txt ,我會感到很高興。 這可能嗎?

使用os.path.expanduser("~")

for line in open(os.path.expanduser("~/my_file")):
    print line

文件:

在Unix和Windows上,返回帶有〜或〜user初始組成部分的參數替換為該用戶的主目錄。

https://docs.python.org/2/library/os.path.html#os.path.expanduser

暫無
暫無

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

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