yao leo yao leo - 1 year ago 59
Python Question

python download images are not saved to the correct directory

When i use python 2.7 to download images from a website, the code as follows:

pic = requests.get(src[0])
f = open("pic\\"+str(i) + '.jpg', "wb")
i += 1

I want to save the picture into pic directory, but I find that images is saved in the same directory with the name like
. Is this a bug?

In Windows, it's right, but on Ubuntu, it's an error!

Answer Source

Windows uses backslashes for file paths, but Ubuntu uses forward slashes. This is why your save path with a backslash doesn't work on Ubuntu.

You probably want to use os.path.join to make your path OS agnostic:

import os
path = os.path.join('pic', '{}.jpg'.format(str(i)))
f = open(path, 'wb)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download