检查是否存在2个文件,以及如果仅存在1个文件,该怎么办。Python 2

检查是否存在2个文件,以及如果仅存在1个文件,该怎么办。Python 2,python,python-2.7,if-statement,Python,Python 2.7,If Statement,在过去的一个小时里,我一直在努力解决这个问题 我似乎无法正确地编写这段基本代码 基本上,我试图检查给定目录中是否存在“jpg.html”和“gif.html” 如果它们都存在,我将jpg\u索引和gif\u索引写入文件。如果只存在“jpg.html”,那么我只将jpg_index写入文件,反之亦然 如果有人能在这里帮助我,那太棒了 这是我的 directory = args['directory'].replace('\\', '/') with open(directory + 'index

在过去的一个小时里,我一直在努力解决这个问题

我似乎无法正确地编写这段基本代码

基本上,我试图检查给定目录中是否存在“jpg.html”和“gif.html”

如果它们都存在,我将
jpg\u索引
gif\u索引
写入文件。如果只存在“jpg.html”,那么我只将
jpg_index
写入文件,反之亦然

如果有人能在这里帮助我,那太棒了

这是我的

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."
directory=args['directory']。替换('\\','/'))
以open(directory+'index.html','w')作为索引:
打印“写入索引文件”
jpg_index=“
\n” gif_index=“
\n” 如果os.path.exists(目录+'jpg.html')和os.path.exists(目录+'gif.html'): index.write(jpg_索引) index.write(gif_索引) index.close() elif os.path.exists(目录+'jpg.html'),而不是os.path.exists(目录+'gif.html'): index.write(jpg_索引) index.close() 如果不是os.path.exists(目录+'jpg.html')和os.path.exists(目录+'gif.html'): index.write(gif_索引) index.close() 打印“完成”
应用注释中的一些更改解决了我的问题

import os
directory = "F:/folder/"

with open(os.path.join(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(os.path.join(directory, 'jpg.html')):
        index.write(jpg_index)
    if os.path.exists(os.path.join(directory, 'gif.html')):
        index.write(gif_index)
print "Complete."
导入操作系统
directory=“F:/folder/”
以open(os.path.join(目录'index.html'),'w')作为索引:
打印“写入索引文件”
jpg_index=“
\n” gif_index=“
\n” 如果os.path.exists(os.path.join(目录'jpg.html')): index.write(jpg_索引) 如果os.path.exists(os.path.join(目录'gif.html')): index.write(gif_索引) 打印“完成”
目录是什么?忘了包括它,但它几乎是我选择的任何文件夹。不过我的问题中增加了这一点。这并没有告诉我们什么是
目录。如果它不是以斜杠结束,那么您将以类似于
usr/binjpg.html
的路径结束,并且您没有提到什么不起作用。啊,好的。我总是加上最后一个斜杠,但我不太确定如果我忘了怎么加。但实际的问题是,在来到这里之前,我尝试了另一个建议的解决方案,但有时它会认为“gif.html”存在,而它不存在,并且会将其写入index.html,因此我尝试了一个更冗余的解决方案,因为我似乎找不到实际的问题。尝试
os.path.join(目录,'jpg.html'))
而不是
目录+'jpg.html'
,否则不包含路径分隔符字符的路径将不适用于目录。