如果文件已存在,Python会跳过一个函数

时间:2012-11-15 13:26:30

标签: python function

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

该功能应如何运作: (如果文件存在则无需运行此代码,只需跳到下一个代码即可。 如果它不存在则运行此代码,然后运行下一个代码)

    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 个答案:

答案 0 :(得分: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)