1

为什么它没有打开我放入函数的文件?当我将文件名直接插入主程序时它会打开,但当我尝试通过函数传递它时不会。它给了我一个FileNotFoundError.

def get_valid_filename(prompt):
  '''Use prompt (a string) to ask the user to type the name of a file. If
  the file does not exist, keep asking until they give a valid filename.
  Return the name of that file.'''

  filename = input(prompt)
  if os.path.isfile(filename) == False:
    print ("That file does not exist.")
    filename = input(prompt)

  return filename

if __name__ == '__main__':

  prompt = 'enter the name of the file with unknown author:'
  mystery_filename = get_valid_filename(prompt)

  # readlines gives us the file as a list of strings each ending in '\n'
  text = open(mystery_filename, 'r').read()

  print (text)
4

1 回答 1

0

get_valid_filename应该是这样的:

def get_valid_filename(prompt):
    while True:
        filename = input(prompt):
        if os.path.exists(filename):
            return filename
        print('that file does not exist')
于 2015-06-03T07:36:11.740 回答