python - 断言 os.path.isfile 仅适用于完整路径

标签 python splinter

我接到了一项教育任务,期间我编写了 Gherkin 场景,以使用 Python 3.6、Splinter 和 Behave 来测试网站。我取得了一些相当好的进展,但我在这件小事上陷入困境。目前,我已经成功地通过 Ubuntu 中的 Chrome headless 实例下载文件。但是,为了让该场景的最后一步通过,我需要验证该文件是否存在。经过大量搜索,我找到了一个可行的方法,即:

assert os.path.isfile('/home/[USERNAME]/Downloads/file.csv')

但是,为了使此测试与其他计算机更兼容,我希望文件的路径更短、更简单。最重要的是,不要使用该系统的用户名。

我对这一切都很陌生,所以这很可能是一个愚蠢的问题,但我一直在到处搜索,但就是找不到答案。

最佳答案

您可以使用 ~ 重写路径,替换 /home/[USERNAME]/,因此它将变为 ~/Downloads/file.csv。然后,您可以使用 Python 的 os.path.expanduser() 函数,如下所示:

assert os.path.isfile(os.path.expanduser('~/Downloads/file.csv'))

os.path.expanderuser() 会自动为您将其扩展为 /home/[USERNAME]/

关于python - 断言 os.path.isfile 仅适用于完整路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53206045/

相关文章:

python - Selenium Python 脚本在 Windows 和 Ubuntu 环境中有不同的行为

python - 无法 pickle 对象 : maximum recursion depth exceeded

随机字母打字测试中的Python Tkinter属性错误条目

python - 在 Python 中,避免对 __init__ 参数和实例变量使用相同名称的最佳方法是什么?

python 碎片 : how to take a screenshot of full page?

python - 如何使用 splinter 填充表格内的输入框?

Python/Django递归模型到树结构字典中

python-3.x - 无法使用 Selenium 和 Splinter 添加 cookie

python - 连接被拒绝且轮询更改失败 : NetworkError when attempting to fetch resource error with Selenium GeckoDriver and Firefox

javascript - 在不关闭 Selenium/Splinter 中的驱动程序的情况下更改代理设置