昨夜、コメント行をすべてファイルから取り出して新しいファイルに出力するプログラムを書きました。これは、私のプログラミングの授業で頻繁にやらなければならないことで、コピーと貼り付けでファイルを選択するのはすぐに慣れてしまいます。
入力ファイルと出力ファイルの両方が存在するかどうかを確認しています。入力ファイルが存在する場合は、すべて続行します。存在しない場合は、別のファイル名を尋ねます。出力ファイルが存在する場合は、上書きするかどうかをユーザーに尋ねます。存在しない場合は、すべて続行します。
私が抱えている問題は、file = open(fileName, 'r') がファイルを見つけられない場合に 1 つのチェックが正しく IOError をスローし、もう 1 つのチェックが IOError を与える代わりに空のファイルを作成することです。
2 ビットのコードがほとんど同じであるため、これは特に不可解です。同じプロセスで、ファイル名変数が異なるだけです...
コードは以下です。2 番目の部分は、空のファイルを作成する部分です。最初に期待どおりにエラーが発生します。
# Try to open the input file
inFileOpen = False
while not inFileOpen and userTrying:
# If it opens, all good
try:
inFile = open(inFileName, 'r')
inFileOpen = True
# If it doesn't open, ask user to try a different file
except IOError:
...
# Try to open the output file
toFileOpen = False
while not toFileOpen and userTrying:
# If the file opens in r mode, that means it exists already, so ask user if they
# want to overwrite the existing file, if not ask for a new file name
try:
# ********************
# For some reason, 'r' mode is creating a file... no clue...
# ********************
toFile = open(toFileName)
toFile.close() # I have tried removing this just guessing at solutions. Didn't work.
# ... Ask if user wants to overwrite
# If the file can't be opened, all good, that means it doesn't exist yet
except IOError:
toFileOpen = False
toFile = open(toFileName, 'w')