我需要在 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"
最佳答案
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)
关于如果文件已存在,Python 会跳过函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13398408/