Pytest-pycharm中右击run正常,在terminal中运行pytest报错:FileNotFoundError: [Errno 2] No such file or directory

with open('..//file//listed_task_delete_ods-log.txt', 'w') as a

是不是我使用相对路径的关系,右击run的时候正常,在terminal运行时就报错 FileNotFoundError: [Errno 2] No such file or directory: '..//file//listed_task_delete_ods-log.txt'

将代码改成with open('file//listed_task_delete_ods-log.txt', 'w') as a,terminal运行正常,右击run就报错,有什么方法解决吗?

这个问题是由于相对路径在Pycharm的右键运行和终端运行时工作目录(Working Directory)不同导致的。在Pycharm中,右键运行默认的工作目录是文件所在的目录,而在终端运行时,默认的工作目录是当前终端所在的目录。

为了解决这个问题,您可以使用Python的os模块来获取文件的绝对路径。这样,无论在Pycharm中右键运行还是在终端中运行,都可以找到正确的文件路径。

以下是使用os模块获取绝对路径的示例代码:

import os

# 获取当前文件的绝对路径
current_file_path = os.path.abspath(__file__)

# 获取当前文件所在目录的路径
current_dir_path = os.path.dirname(current_file_path)

# 构建目标文件的绝对路径
target_file_path = os.path.join(current_dir_path, 'file', 'listed_task_delete_ods-log.txt')

# 使用绝对路径打开文件
with open(target_file_path, 'w') as a:
    pass

这样,无论是在Pycharm中右键运行还是在终端运行,都可以正确找到并打开文件。

不知道你这个问题是否已经解决, 如果还没有解决的话:

如果你已经解决了该问题, 非常希望你能够分享一下解决方案, 写成博客, 将相关链接放在评论区, 以帮助更多的人 ^-^