如何让此程序在任何操作系统上查找Pictures文件夹?E、 g.Windows、Linux和Mac.

我的程序只需要输入并创建一个QRcode图像.

我知道有一些标准模块可以帮助我,比如ossys,但我无法自己解决这个问题.

import qrcode

data = 'This is an example.'
qr = qrcode.QRCode(version=1)
qr.add_data(data)
img = qr.make_image(fill_color='white', back_color='purple')
img.save('$HOME/Pictures/qrcode_make_python.png')

推荐答案

首先你应该判断操作系统,我建议使用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!")

Python-3.x相关问答推荐

使用魔方无法从图像中识别单个字符

给定panda代码的分组和百分比分布pyspark等价

如何将从维基百科表中抓取的数据转换为字典列表?

将数据框中的值与另一个数据框中的多列进行比较,以获取条目以有效方式匹配的列表列表

使用gekko python的混合整数非线性规划

为什么 mypy 不适用于 sqlalchemy?

位对的距离

裁剪复数以解决 exp 中的溢出错误

XPATH:使用 .find_elements_by_xpath 为未知数量的 xpath 输入值

pip 找不到最新的软件包版本

段落中句子的索引

魔术8球txt文件列表

删除重复项,但将值相加为一

Python:获取未绑定的类方法

将字符串表示与使用整数值的枚举相关联?

具有两个或多个返回参数的函数注释

Python图例属性错误

判断 dict.items() 中的成员资格的时间复杂度是多少?

使用 urllib3 忽略证书验证

使用 Python 3 读取 CSV 文件