如何检查文件是否已存在,如果不存在,请在 Python 下载?

How to check if file already exists, if not, download on Python?

我正在使用 Python 从 Flickr 下载图片(我的最爱),但是当我执行此过程时,我想检查图片是否已经下载。 我尝试将下载文件的 ID 写入 TXT 文件并进行检查,但不起作用。

例如 我下载了最后 5 张我标记为收藏的图像,我已经下载了它们,但我标记了另一个图像,所以 N1 尚未下载,但其他 4 张已下载,所以我只想下载 "missing"一个,而不是其他 4 个。

我获取图像但 if 不起作用的部分:

for item in pics:
if item['id'] in open("id.txt").read():
    print "Exists"
else:
    file.write(item['id'] + "\n")
    image = str("http://www.flickr.com/" + item['owner'] + "/" + item['id'] + "/sizes/l/")
    website = urllib2.urlopen(image)
    html = website.read()
    links = re.findall('"((http)s?://.*?)"', html)
    filter = links[0][0]
    end = filter.replace("_m.jpg", "_b.jpg")
    urllib.urlretrieve(end, "FlickFavorite(" + str(n) + ").jpg")
    print ult
    n += 1

非常感谢您的帮助!

import os

os.path.isfile(file_to_check)

会完成任务的。

os.path.exists(file_to_check) 

也可以,但 return 也适用于目录。这可能不是你一直想要的。

如果您想检查已知目录中的多个文件,一种方法是:您可以使用

获取文件(和目录)列表
file_list = os.listdir(directory_to_check)

然后遍历文件列表,可能会检查列表中您感兴趣的文件名的匹配项,然后检查每个文件是否存在。