1

我需要在 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"
4

1 回答 1

4
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)
于 2012-11-15T13:29:13.053 回答