首页 > 解决方案 > 无法打开 Python 上的文件(os.startfile)

问题描述

我有一个保存搜索结果(路径)的文件。我只希望打开第一个结果。我这样做了:

        with open('search_results.txt','r') as f:
            newest_file = str(f.readline().splitlines())
        print(newest_file)
         os.startfile(newest_file)

打印结果为:O:/111/222/test_99.zip' 但错误为:FileNotFoundError: [WinError 2] 系统找不到指定的文件:O:/111/222/test_99.zip' 补充:O:是网络上的驱动器

我也尝试替换斜线

latest_file = latest_file.replace('/','\\')

标签: pythonpython-3.x

解决方案


这是您的问题的解决方案,您正在使用splitlines它的边界弄乱了您的文件路径,因此,您的脚本引发了FileNotFoundError异常。使用常规拆分可以实现您想要的。

import os
with open('search_results.txt','r') as f:
        newest_file = f.read().split("\n")[0] # Reading the file, spliting it by new lines, and getting the first result
        os.startfile(newest_file)

推荐阅读