简体   繁体   中英

Python3 - CSV Writer Sort by Date

I have some problems creating a Python script and hope that you can help me.

The script should read the exif information (date, time and GPSInfo) from multiple images and write the results sorted by date into a CSV file.

Currently I manage to write the data into the CSV file. But I don't manage to sort the entries by date.

# for every file in the directory get the latlng
for file in os.listdir("/path/"):
    if file.endswith(".jpg" or ".png"):
        path_name = '/path'+ file
        meta_data =  ImageMetaData(path_name)
        latlng =meta_data.get_lat_lng()
        date = meta_data.date
        print(latlng, date)
        with open('dez.csv', 'w', newline='') as csvfile:
            spamwriter = csv.writer(csvfile, delimiter=' ',
                            quotechar='|', quoting=csv.QUOTE_MINIMAL)
            for x in range(0, 10):
                spamwriter.writerow(latlng)
                spamwriter.writerow(date)

Since you said you don't want the actual date in the output CSV, you should build a dictionary mapping date s to lat_lng pairs, sort the keys of the dict and then write each value of the dict to a CSV.

from pathlib import Path

IMAGE_DIRECTORY = Path("/home/user/Schreibtisch/recoveredPictures/")

images = list(IMAGE_DIRECTORY.glob("*.jpg")) + list(IMAGE_DIRECTORY.glob("*.png"))

date_to_lat_lng = {}
for image in images:
    meta_data = ImageMetaData(path_name)
    lat_lng = meta_data.get_lat_lng()
    date = meta_data.get_date_time()
    date_to_lat_lng[date] = [lat_lng[0], lat_lng[1]]

with open("test.csv", "w", newline="") as csvfile:
    writer = csv.writer(csvfile, delimiter="\t")
    for date in sorted(date_to_lat_lng):
        writer.writerow(date_to_lat_lng[date])

(Updated with all the changes you asked for in the comments)

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