Python 3.x 创建向用户请求文件的函数

Python 3.x 创建向用户请求文件的函数,python-3.x,file-io,Python 3.x,File Io,我正在尝试创建一个函数,该函数要求用户输入文件名。如果找不到该文件,它将继续询问。这是我的东西,请帮忙 def return_text_file(infile): while infile: try: file = open(infile) except IOError: print("Could not find the file specified") infile = inp

我正在尝试创建一个函数,该函数要求用户输入文件名。如果找不到该文件,它将继续询问。这是我的东西,请帮忙

def return_text_file(infile):
    while infile:

        try:
            file = open(infile)
        except IOError:

            print("Could not find the file specified")
            infile = input ("Enter the file name")
    return open_infile

您可以创建一个函数(例如下面的
ask\u file\u name
)从用户处获取有效答案。它将不断重复,直到给出现有名称

import os

path_str = '/home/userblabla/ProjectBlabla/'


def ask_file_name():
    files_detected = os.listdir(path_str)

    while True:
        print('\nFiles:')
        for file in files_detected:
            print(file)

        file_name_given = input('\nFile name?')
        if file_name_given not in files_detected:
            print("Could not find the file specified")

        else:
            print('Thanks friend.')
            return file_name_given

my_file_name = ask_file_name()

with open(my_file_name, 'r') as opened_file:
    # Do stuff on opened_file
    ......

with open()
会自动关闭文件,如果您使用它而不是
open()

可能会更好。问题是什么?我能想到的一件事是,你没有一个
break
语句,而跳出我的第一件事是,你正在返回open_infle,这是以前没有定义过的
import os

path_str = '/home/userblabla/ProjectBlabla/'


def ask_file_name():
    files_detected = os.listdir(path_str)

    while True:
        print('\nFiles:')
        for file in files_detected:
            print(file)

        file_name_given = input('\nFile name?')
        if file_name_given not in files_detected:
            print("Could not find the file specified")

        else:
            print('Thanks friend.')
            return file_name_given

my_file_name = ask_file_name()

with open(my_file_name, 'r') as opened_file:
    # Do stuff on opened_file
    ......