Python 不断提示用户输入正确的文件目录,并将输入存储在变量中

Python 不断提示用户输入正确的文件目录,并将输入存储在变量中,python,Python,这是我的代码的开始,它获取一个数据集并使用matplotlib对其进行打印。但是,我想创建一个while循环,提示用户提供文件的正确路径或目录,例如/Users/Hello/Desktop/file.txt 当用户没有输入正确的路径时,循环应该不断提示输入目录 如果该路径中确实存在文件,则应将该输入存储在变量路径中,该变量路径稍后用于显示数据 如果没有文件,它应该再次询问 我的while循环似乎卡在了第一个print语句中 import pandas as pd import matplotli

这是我的代码的开始,它获取一个数据集并使用matplotlib对其进行打印。但是,我想创建一个while循环,提示用户提供文件的正确路径或目录,例如/Users/Hello/Desktop/file.txt

当用户没有输入正确的路径时,循环应该不断提示输入目录

如果该路径中确实存在文件,则应将该输入存储在变量路径中,该变量路径稍后用于显示数据

如果没有文件,它应该再次询问

我的while循环似乎卡在了第一个print语句中

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import itertools
import os


# This is the correct directory: os.path.isfile('/Users/Hello/Desktop/file.txt')

""" 
Prompt the user for the right directory to the file.
If the file is not there, ask again.
If the path is correct, store it in the variable Path.
"""

correct = os.path.isfile(directory)

directory = input("Please provide the correct directory to the dataset  ")

    while os.path.isfile == False:

        if os.path.isfile(Directory) != True:
            directory = ath
            print('Thank you')
        elif os.path.isfile(Directory) == True:
            print("This directory does not exist, please try again.")


#this variable inserts the users input and displays the data in the file

dframe = pd.read_table(path, delim_whitespace=True, names=('X','Y'),
                   dtype={'X': np.float64, 'Y':np.float64})

dframe.head(10) # show the first 10 rows of the data

您发布的示例代码在语法上不正确

与前一行相比,while块不应缩进。 在定义目录之前使用它 要直接回答您的问题,在打印“谢谢”之后,您需要有一个中断语句来中断while循环


您的while循环不变量也不正确-您正在检查os.path.isfile是否为False。os.path.isfile是一个函数,函数是真实的。您有效地编写了while True:-这是正确的,但它并没有执行您可能认为它正在执行的操作。

编写一个函数。您的代码有多个问题,但我想您希望这样

def prompt_for_filepath():
    """ 
    Prompt the user for the right path to the file.
    If the file is not there, ask again.
    If the path is correct, return it.
    """
    while True:        
        path = input("Please provide the correct path to the dataset")    
        if os.path.isfile(path):
            return path
        print("This path does not exist, please try again.")

您的循环条件没有意义。isfile是一个函数,需要检查路径。您还需要调用directory=input。。。再次在while循环中实际检索另一个输入。为什么不使用文件对话框以便用户输入文件?在while循环中,您需要在if和elif语句中移交目录os.path.isfiledirectory,使用小写字母“d”与变量匹配如果这是用于桌面,python标准库包含tkinter.filedialog,它提供了一个您可以使用的跨平台gui对话窗口。可能重复的