继续提示用户输入正确的目录,将输入存储在变量中

时间:2018-04-30 20:29:20

标签: python

这是我的代码的开头,它采用数据集并使用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

2 个答案:

答案 0 :(得分:1)

写一个函数。你的代码有很多问题,但我想你想要这样的东西。

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.")

答案 1 :(得分:0)

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

  • 与前一行相比,while块不应缩进。
  • directory在定义之前使用

要在print('Thank you')之后直接回答您的问题,您需要使用break语句来摆脱while循环。

您的while循环不变也不正确 - 您要检查os.path.isfile是否为False。 os.path.isfile是一个功能,功能是真实的。你有效地写了while True: - 这不是错误的,但它并没有做你认为它正在做的事情。