2012-11-15 50 views
0

如果文件已经存在,我需要在python中创建一个跳过函数,跳过我的下载代码。如果文件已经存在,Python跳过一个函数

怎样的功能应该工作: (如果存在该文件无需运行这段代码,就跳到下一个代码 如果它不存在,然后运行该代码,然后运行下面的代码。)

Filecheck = os.path.join(OUTPUT_FOLDER,"test"+version+"exe") 
    print Filecheck 

    if not os.path.exists(Filecheck): 


    base_url = urlJoin(LINK, + version + "_multi.exe") 
    print base_url 

    filename2 = "%s_%s_.exe" % (software.capitalize(),version) 
    original_filename = os.path.join(OUTPUT_FOLDER, filename2) 


    if writeFile(original_filename, httpRequestFile(base_url), "wb") and os.path.exists(original_filename): 
     print "Download done" 
+1

你或许可以使用答案[我如何检查文件是否存在使用Python?](http://stackoverflow.com/questions/82831/how-do-i-check-if-a-file-exists-using-python) –

回答

3
if not os.path.exists(<path-to-file>): 
    download_file() 

我猜这就是你的意思,虽然这是非常难以判断。

filename = "%s_%s_.exe" % (software.capitalize(),version) 
if not os.path.exists(os.path.join(OUTPUT_FOLDER, filename)): 
    base_url = urlJoin(LINK, + version + "_multi.exe") 
    writeFile(original_filename, httpRequestFile(base_url), "wb") 

仅供参考,如果你使用requests你不需要httpRequestFile,所以您可以简化代码:

import requests 
from urllib2 import urljoin 
filename = "%s_%s_.exe" % (software.capitalize(),version) 
if not os.path.exists(os.path.join(OUTPUT_FOLDER, filename)): 
    with open(filename, "wb") as fp: 
     fp.write(requests.get(urljoin(LINK, version + "_multi.exe")).content) 
+0

如果该文件存在? – user1823753

+0

_如果文件存在? – katrielalex

+0

所以你的意思是,它应该看起来像这样?查看我的更改 – user1823753

相关问题