Search code examples
pythonexiffolium

Not getting the full output out of a list


Objective

I'm trying to extract the GPS "Latitude" and "Longitude" data from a bunch of JPG's and I have been successful so far but my main problem is that when I try to write the coordinates to a text file for example I see that only 1 set of coordinates was written compared to my console output which shows that every image was extracted. Here is an example: Console Output and here is my text file that is supposed be a mirror output along my console: Text file

I don't fully understand whats the problem and why it won't just write all of them instead of one. I believe it is being overwritten somehow or the 'GPSPhoto' module is causing some issues.


Code

from glob import glob
from GPSPhoto import gpsphoto

# Scan jpg's that are located in the same directory.
data = glob("*.jpg")

# Scan contents of images and GPS values.
for x in data:
    data = gpsphoto.getGPSData(x)
    data = [data.get("Latitude"), data.get("Longitude")]
    print("\nsource: {}".format(x), "\n ↪ {}".format(data))

# Write coordinates to a text file.
with open('output.txt', 'w') as f:
    print('Coordinates:', data, file=f)

I have tried pretty much everything that I can think of including: changing the write permissions, not using glob, no loops, loops, lists, no lists, different ways to write to the file, etc. Any help is appreciated because I am completely lost at this point. Thank you.


Solution

  • You're replacing the data variable each time through the loop, not appending to a list.

    all_coords = []
    for x in data:
        data = gpsphoto.getGPSData(x)
        all_coords.append([data.get("Latitude"), data.get("Longitude")])
    
    with open('output.txt', 'w') as f:
        print('Coordinates:', all_coords, file=f)