python中关于当前目录的问题

如果是在调试终端执行脚本,那么current_dir 往往不是脚本文件本身所在的当前目录,通过获取脚本文件所在目录就可以了。

    # 获取当前目录的路径
    current_dir = os.getcwd()
    # 获取脚本文件所在目录的路径
    script_dir = os.path.dirname(os.path.realpath(__file__))

    # 在当前目录下创建文件
    file_path = os.path.join(script_dir, 'tips.txt')
    with open(file_path, 'w') as f:
        f.write(tips_msg)

    print('File created successfully.')



发表评论 / Comment

提示:本文章评论功能已关闭