【问题标题】:How to get path to python file running through open with如何获取通过打开运行的python文件的路径
【发布时间】:2019-08-20 17:13:06
【问题描述】:

我似乎无法访问我在“打开方式”上使用的文件路径

我正在创建自己的文本编辑器,可以通过打开选项卡(工作)打开文件,也可以使用从脚本转换的 .exe 文件打开 .txt 文件

我尝试了很多不同的方法来访问该文件,但似乎没有任何效果

try:
    fileName = str(os.path.realpath(__file__))
    with open(fileName) as _file:
        contentText.insert(1.0, _file.read())
    onContentChanged()
    root.title(os.path.basename(fileName) + " - Footprint Editor")
except:
    root.title("Untitled - Footprint Editor")

我尝试让 fileName 等于我使用“打开方式”的文件的路径 当 .py 文件转换为 .exe 时

【问题讨论】:

    标签: python file system


    【解决方案1】:

    使用_file.name 获取您打开的文件的路径

    with open(fileName) as _file:
            print(f.name)
    

    但如果您想在with open 之外查看路径,您可能只需要使用open 而不是with open

    _file=open(fileName)
    # Do some stuff if you want here
    print(_file.name)
    

    【讨论】:

    • 这适用于我加载新文件,但不适用于我使用 open-with on 的初始文件,因为某些奇怪的原因,我认为这可能是因为 fileName 之前设置为 None开,我应该改变它,只把None放在除外吗?
    • 似乎在开始时删除fileName = None 不起作用,因此您似乎需要一些模块或类似的东西。
    • 我不明白,您是要查找当前正在运行的文件的路径还是使用with open 或打开的文件的路径?
    • 对不起!!我试图让程序访问我使用open-with打开的文件的路径@
    • 你知道我该如何解决这个问题吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多