【问题标题】:user input forget to key in the file name or accidentally press enter without break the program用户输入忘记键入文件名或不小心按回车而不中断程序
【发布时间】:2020-08-18 04:04:24
【问题描述】:

如果用户忘记插入文件扩展名或错误的文件名,或者在没有输入文件名的情况下不小心按 Enter 键,我不希望此脚本关闭或结束。我该怎么做?

def sum_usage():

    file_name = []
    print('\tMake sure the file is on the same directory with this script!')
    
    while True:
        file_name = input('\tEnter file name with file extension (.xlsx): ')
        if file_name == file_name:
            print('\n')
            print(file_name)
            df = pd.read_excel(file_name, index_col = 0)
            print(tabulate(df, headers = ['Access SSID', 'Radio Frequencies', 'User Count', 'Total Traffic'], tablefmt = 'psql'))
            break
        else:
            print('There is no file name. Please enter correct file name.')

这里出了点问题,但我不确定:

file_name = input('\tEnter file name with file extension (.xlsx): ')
        if file_name == file_name:
            print('\n')
            print(file_name)
            df = pd.read_excel(file_name, index_col = 0)
            print(tabulate(df, headers = ['Access SSID', 'Radio Frequencies', 'User Count', 'Total Traffic'], tablefmt = 'psql'))

【问题讨论】:

    标签: python-3.x pandas list


    【解决方案1】:

    您需要检查文件名是否为空。

    例子:

    def sum_usage():
        file_name = []
        print('\tMake sure the file is on the same directory with this script!')
        
        while True:
            file_name = input('\tEnter file name with file extension (.xlsx): ')
            if file_name.strip() != '':
                print('\n')
                print(file_name)
                df = pd.read_excel(file_name, index_col = 0)
                print(tabulate(df, headers = ['Access SSID', 'Radio Frequencies', 'User Count', 'Total Traffic'], tablefmt = 'psql'))
                break
            else:
                print('There is no file name. Please enter correct file name.')
    

    【讨论】:

      【解决方案2】:

      是的,我找到了解决我自己问题的方法。

          while True:
              file_name = input('\tEnter file name: ')
              if os.path.exists(file_name):  # I add this statement to check if the file exist or not.
                  with open(file_name) as df:
                      print('\n')
                      print(file_name)
                      df = pd.read_excel(file_name, index_col = 0)
                      print(tabulate(df, headers = ['Access SSID', 'Radio Frequencies', 'User Count', 'Total Traffic'], tablefmt = 'psql'))
                      break
              else:
                  print('\tMake sure you enter correct file name with the file extension')
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-04-07
        • 2011-07-12
        • 2012-12-23
        • 1970-01-01
        • 2015-04-01
        • 2015-02-17
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多