2017-12-19 6 views
0

テキストファイルから画像URLを読み取り、画像をダウンロードして同じフォルダに保存する次のPythonスクリプトがあります。イメージは何らかの理由でファイルにダウンロードされています画像をPythonでダウンロードする保存時に疑問符で終了する

# this script is used to download the images using the provided url 
import requests 
import ntpath 


# save image data 
def save_image_data(image_data,file_name): 
    with open(file_name,'wb') as file_object: 
     file_object.write(image_data) 

# read the images_url file 
with open('images_urls_small.txt') as file_object: 
    for line in file_object: 
     file_name = ntpath.basename(line) 
     print(file_name) 
     # download the image 
     try: 
      image_data = requests.get(line).content 
     except: 
      print("error download an image") 
     # save the image 
     save_image_data(image_data,file_name) 

イメージは正常にダウンロードされますが、理由はありますか?下のスクリーンショットに示すようにファイル名の後ろに入力します。

enter image description here

私は何をしないのですか?

+3

'save_image_data'関数の' print(ascii(file_name)) 'には何が表示されますか?最後は改行( '\ n')です。それらを取り除く。 –

+0

ありがとう!はい、あなたはそれが正しいです。あなたが答えとしてそれを置くことができるなら、私はできるだけ早くそれを受け入れることができます:) –

答えて

1

あなたはファイルからファイル名を取っ:

for line in file_object: 
    file_name = ntpath.basename(line) 

しかし、それらの行はまだ行区切り(改行文字なので、\n)はinscludedています。あなたの行を削除してください:

for line in file_object: 
    file_name = ntpath.basename(line.strip()) 
関連する問題