【问题标题】:Automating uploading files via asking filepath from user in python通过在python中向用户询问文件路径来自动上传文件
【发布时间】:2020-07-05 15:20:30
【问题描述】:
# This module takes path of any random dataset from the user

class User_Input():
  # Taking File Path as input from the user
  user_input = input("Enter the path of your file: ")

  # The assert keyword lets you test if a condition in your code returns True, if not, the program will raise an AssertionError.
  assert os.path.exists(user_input), " did not find the file at, "+str(user_input)
  user_file = open(user_input,'r+')

  print(" found the file !")

  for fp in user_file:
      # Split the extension from the path and normalise it to lowercase.
      ext = os.path.splitext(fp)[-1].lower().suffix()

      # For handling breakdown in case of any errors
      try:
        # Now we can simply use .endswith to check for equality, no need for wildcards.
        # For handling csv files
        if ext.endswith('.csv'):
            df = pd.read_csv(user_input)

        # For handling excel files
        elif ext.endswith('.xlsx'):
            df = pd.read_excel(user_input)

        # For handling json files
        elif ext.endswith('.json'):
            df = pd.read_json(user_input)

        # For handing unknown files types
        else:
            print( fp,"is an unknown file format.")
            break

      # to handle the situation if try block gets failed
      except:
          pass

  user_file.close()

        
 

我正在尝试自动上传任何文件扩展名(如 .csv、.json、.xlsx 等)并读取数据框中的代码。但是,这显示了断言错误,但我提供了正确的路径?编码也有问题!

它不能中断并告诉用户任何错误!

【问题讨论】:

    标签: python json excel csv


    【解决方案1】:

    断言错误由您的assert 语句引发,该语句位于try 块之外,因此引发的错误不会被except 语句捕获。

    更好的选择可能是完全删除断言并在try 块中打开文件:

    try:
        with open(user_input, "r+") as file:
               # process file contents
    except:
        pass
    

    如果路径无效,FileNotFound 将在 try 块中安全地引发错误。

    【讨论】:

    • 你的意思是,我必须在断言之前再使用一个 try 块。
    • 没有理由这样做。您可以在 open 语句周围移动 try 块。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-08
    • 1970-01-01
    • 1970-01-01
    • 2014-01-19
    • 2013-01-23
    相关资源
    最近更新 更多