python - 通过在 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 等)并读取数据框中的代码。但是,这显示了断言错误,但我提供了正确的路径?编码也有问题!
它不能破坏并告诉用户任何错误!
解决方案
Assertion 错误由您的assert
语句引发,该语句位于try
块之外,因此引发的错误不会被except
语句捕获。
更好的选择可能是完全删除断言并在try
块中打开文件:
try:
with open(user_input, "r+") as file:
# process file contents
except:
pass
如果路径无效,将在块FileNotFound
中安全地引发错误。try
推荐阅读
- javascript - Javascript JQuery警报弹出窗口未显示
- java - 无法使用 Java 10 和 Java 11 运行或导入 JAR
- node.js - 如何从 forever.js 中删除 --minUptime 警告
- java - 异步 api 的反射
- node.js - cd 以更正 package.json 中的文件夹
- google-bigquery - BigQuery 与其他类型数据库的关系
- linux - Jenkins Pipeline Script:通过发送电子邮件通知
- c++ - 在 C++ 中将对象转换为派生类型
- node.js - 检查 findOne mongodb nodejs 的结果
- html - 定位横幅