简体   繁体   中英

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('/','\\')

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM