简体   繁体   中英

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")
f.write(pic.content)
f.close()
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 pic\\1.jpg . Is this a bug?

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

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)
...
import os
f = open(os.sep.join(['pic', str(i), '.jpg']), 'wb')

Now the line should be os agnostic

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM