2016-12-18 8 views
-2

私はこの1時間の間これに苦労してきました。2つのファイルが存在するかどうかをチェックし、1つだけ存在する場合はどうするかを確認します。 Python 2

この基本ブロックを正しく書くことができません。

基本的には、特定のディレクトリに "jpg.html"と "gif.html"が存在するかどうかを確認しようとしています。

両方とも存在する場合は、jpg_indexgif_indexをファイルに書き込みます。 "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." 
+0

「ディレクトリ」とは何ですか? – TigerhawkT3

+0

それを含めるのを忘れましたが、私が選んだフォルダはほとんどありません。私の質問にそれを加えました。 – dxrth

+1

これは 'ディレクトリ 'が何であるかを正確に教えてくれません。スラッシュで終わっていない場合は、 'usr/binjpg.html'のようなパスで終わるでしょうし、うまくいきませんでした。 – TigerhawkT3

答えて

1

コメントの変更の一部が私の問題を解決しました。

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." 
関連する問題