Skip to main content
 首页 » 编程设计

python之使用 os.expanduser (python) 后查找文件目录

2024年12月31日8lyhabc

我的程序使用以下方法在用户桌面上创建一个日志文件:

file = open(os.path.expanduser("~/Desktop/Log.txt"), 'a') 

但稍后我需要使用 MIME 将日志文件发回给自己。要发送文件,它需要文件目录,但我不知道如何找到它?我试过这样做:

filename='(os.path.expanduser("~/Desktop/Log.txt"), 'a')' 

但这行不通。还有另一种方法吗?如果有那么请举个例子,因为我是初学者并且真的不知道我在做什么。

请您参考如下方法:

你试过这个吗?看看它是否有效。

directory=os.path.dirname(os.path.expanduser("~/Desktop/Log.txt")) 

如果你想要绝对路径试试

fullpath=os.path.abspath(os.path.expanduser("~/Desktop/Log.txt")) 

更多方便的功能在这里:

https://docs.python.org/3/library/os.path.html