昨晚我写了一个程序,它把所有注释的行从一个文件中拉出来,然后输出到一个新文件中。这是我们在我的编程课上经常要做的事情,并且通过文件复制和粘贴来挑选很快就会变老。
我检查了我的输入文件和输出文件以查看它们是否存在。如果输入文件确实存在,那么一切都会继续——如果不存在,请询问另一个文件名。如果输出文件确实存在,询问用户是否要覆盖——如果它不存在,一切都很好。
我遇到的问题是,当 file = open(fileName, 'r') 找不到文件时,一项检查正确地引发 IOError,另一项检查创建一个空白文件而不是给出 IOError。
这尤其令人困惑,因为这两位代码几乎相同。相同的过程,只是不同的文件名变量......
代码如下。第二部分是创建空白文件的部分。首先按预期给出错误。
# 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')