繁体   English   中英

通过向 python 中的用户询问文件路径自动上传文件

[英]Automating uploading files via asking filepath from user in 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 等)并阅读 dataframe 中的代码。 但是,这显示了断言错误,但我提供了正确的路径? 编码也有问题!

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

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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM