dimanche 18 décembre 2016

Checking if 2 files exist, and what to do if only 1 exists. Python 2

I've been struggling with this for the last hour.

I can't seem to write this basic block of code correctly.

Basically, I'm trying to check if "jpg.html" and "gif.html" exist in a given directory.

If they both exist I write jpg_index and gif_index to the file. If only "jpg.html" exists, then I only write jpg_index to the file, and vice versa.

If anyone can help me here, that would be amazing!

Here's what I have.

directory = args['directory'].replace('\\', '/')

with open(directory + 'index.html', 'w') as index:

print "Writing index file."

jpg_index = "<a href='jpg.html'>jpg</a><br />\n"
gif_index = "<a href='gif.html'>gif</a><br />\n"

if os.path.exists(directory + 'jpg.html') and os.path.exists(directory + 'gif.html'):
    index.write(jpg_index)
    index.write(gif_index)
    index.close()
elif os.path.exists(directory + 'jpg.html') and not os.path.exists(directory + 'gif.html'):
    index.write(jpg_index)
    index.close()
elif not os.path.exists(directory + 'jpg.html') and os.path.exists(directory + 'gif.html'):
    index.write(gif_index)
    index.close()
print "Complete."

Aucun commentaire:

Enregistrer un commentaire