Search code examples
pythonflickrwritefile

Writing to a file in python


In the following code I simply want to write the data I obtained from flickr in a neat way in a file for use later. However although the console throws no errors, nothing is being written to my file. Can anyone help me out with this, thank you in advance!

import flickrapi

api_key = "xxxxxxxxxxx"
secret_api_key = "xxxxxxxxxxxxxxxx"
flickr = flickrapi.FlickrAPI(api_key, secret_api_key)

def obtainImages():

    photo_list = flickr.photos.search(api_key=api_key, has_geo=1, per_page = 500)
    file = open("obtainedImages.txt", "w")

    for photo in photo_list[0]:
        photo_location = flickr.photos_geo_getLocation(photo_id=photo.attrib['id'])

        id = str(photo[0].attrib['id'])
        lat = str(photo_location[0][0].attrib['latitude'])
        long = str(photo_location[0][0].attrib['longitude'])

        file.write("%s" %id)
        file.write(' ')
        file.write("%s" % lat)
        file.write(' ')
        file.write("%s" % long)
        file.write('\n')

obtainImages()

Here is updated code, that is again showing no errors but is not writing anything to the file. Lat and lon are printing ok

import flickrapi

api_key = "xxxxxxxxxxxxxxxxx"
secret_api_key = "xxxxxxxxx"
flickr = flickrapi.FlickrAPI(api_key, secret_api_key)

def obtainImages():

    photo_list = flickr.photos.search(api_key=api_key, has_geo=1, per_page = 500)
    file = open("obtainedImages.txt", "w")

    for photo in photo_list[0]:

        photo_location = flickr.photos_geo_getLocation(photo_id=photo.attrib['id'])
        lat = str(photo_location[0][0].attrib['latitude'])
        long = str(photo_location[0][0].attrib['longitude'])

        file.write("%s" % lat)
        file.write(' ')
        file.write("%s" % long)
        file.write('\n')

    file.close()
obtainImages()

Solution

  • Add file.close() at the end of your obtainImages() method.

    def obtainImages():
    
        photo_list = flickr.photos.search(api_key=api_key, has_geo=1, per_page = 500)
        file = open("obtainedImages.txt", "w")
    
        for photo in photo_list[0]:
            photo_location = flickr.photos_geo_getLocation(photo_id=photo.attrib['id'])
    
            id = str(photo[0].attrib['id'])
            lat = str(photo_location[0][0].attrib['latitude'])
            long = str(photo_location[0][0].attrib['longitude'])
    
            file.write("%s" %id)
            file.write(' ')
            file.write("%s" % lat)
            file.write(' ')
            file.write("%s" % long)
            file.write('\n')
        file.close()  ## add here