首页 > 解决方案 > 通过在 python 中向用户询问文件路径来自动上传文件

问题描述

# 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 等)并读取数据框中的代码。但是,这显示了断言错误,但我提供了正确的路径?编码也有问题!

它不能破坏并告诉用户任何错误!

标签: pythonjsonexcelcsv

解决方案


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

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

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

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


推荐阅读