首先你应该判断操作系统,我建议使用sys.platform
import sys
if sys.platform == 'win32':
print("You are in windows")
elif sys.platform == 'darwin':
print("You are in MacOS")
elif sys.platform == 'linux' or sys.platform=='linux2':
print("You are in Linux')
要获得windows中的用户路径,我们将使用os.expanduser("~")
,这将获得要插入的路径.
要获取目录,我们将使用以下设置:
import sys
import os
if sys.platform=='linux' or sys.platform=='linux2':
img.save("~/Pictures/qrcode_make_python.png")
elif sys.platform == 'win32':
userpath = os.expanduser("~")
img.save(f"{userpath}\\Pictures\\qrcode_make_python.png")
elif sys.platform == 'darwin':
img.save("${HOME}/Pictures/qrcode_make_python.png")
else:
# Use file stderr if you want to communicate an error
print("ERROR: unrecognized operating system!",file=sys.stderr)
# or you could do
# sys.stderr.write("ERROR: unrecognized operating system!")
或者我们可以使用windows api直接获取信息:
import sys
import win32com.shell as shell
import win32com.shell.win32con as con
if sys.platform=='linux' or sys.platform=='linux2':
img.save("~/Pictures/qrcode_make_python.png")
elif sys.platform == 'win32':
picturesfolder = shell.SHGetSpecialFolder(0,con.CSIDL_MYPICTURES)
img.save(f"{picturesfolder}\\qrcode_make_python.png")
elif sys.platform == 'darwin':
img.save("${HOME}/Pictures/qrcode_make_python.png")
else:
# Use file stderr if you want to communicate an error
print("ERROR: unrecognized operating system!",file=sys.stderr)
这并不坏,但如果我们想制作一个几乎适用于所有操作系统的解决方案,并且占用更少的空间,那么我们可以使用pathlib.Path.expanduser()
或pathlib.Path.home()
来获取当前用户的主目录.
然后我们可以做的是将其添加到'Pictures'
,就完成了,下面是一个我们如何实现这一点的示例:
import pathlib
to_save = pathlib.Path.home()/'Pictures'/'qrcode_make_python.png'
if to_save.exists():
img.save(to_save)
else:
print("WARNING: Default path is not avaiable, downloading in same directory.")
img.save("qrcode_make_python.png")
print("Image Saved!")