Skip to content
Advertisement

File on Python (os.startfile) can’t be opend

I have a file in which search results (paths) are saved. I only want the very first result to be opend. I did this with:

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

The print result is: O:/111/222/test_99.zip’ But the error is: FileNotFoundError: [WinError 2] system cannot find the file specified: O:/111/222/test_99.zip’ An addition: O: Is a drive on the network

I tried also to replace the slashes

newest_file = newest_file.replace(‘/’,’\’)

Advertisement

Answer

Here is a solution to your problem, you were using splitlines which its boundaries were messing up your file path, thus, your script raised the FileNotFoundError exception. Using regular split could achieve what you wanted.

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)
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement