简体   繁体   English

我想检查传入的文件(导入的文件)是否是 python 中的 .csv 或 .xls 或 .xlxs

[英]I would like to check if an incoming file (the imported file) is a .csv or .xls or .xlxs in python

My problem statement is to find if the imported file is a CSV or EXCEL file in pandas.我的问题陈述是在pandas中查找导入的文件是CSV还是EXCEL文件。 The input will be given from the command line as sys.argv[1] where sys.argv[1] is 'D:/Users/abc'输入将从命令行作为 sys.argv[1] 给出,其中 sys.argv[1] 是 'D:/Users/abc'

When the path along with file name is given in command line as a parameter, I have to check inside my script if sys.argv[1] is a CSV or EXCEL file当路径和文件名在命令行中作为参数给出时,我必须检查我的脚本内部是否 sys.argv[1] 是 CSV 或 EXCEL 文件

eg: python myscript.py D:/Users/abc [abc is the file name]例如:python myscript.py D:/Users/abc [abc 是文件名]

This should say if the file is CSV or EXCEL这应该说明文件是 CSV 还是 EXCEL

I tried referring the answers from below link, but could not find exactly what I am looking for!我尝试从下面的链接中引用答案,但找不到我正在寻找的内容!

How to check the uploaded file is csv or xls in python? 如何在python中检查上传的文件是csv还是xls?

Any help would be highly appreciated任何帮助将不胜感激

Since you give the filename "abc" as an example, I assume that you cannot decide on the file type based on extension.由于您以文件名“abc”为例,我假设您无法根据扩展名决定文件类型。 There are ways to look for the magic string in the header of the file, but that would be hard to get foolproof.有多种方法可以在文件头中查找魔法字符串,但很难做到万无一失。

However, it is easier to ask for forgiveness than permission .然而,请求原谅比许可容易 So why don't you just assume it is an excel file, try to read it with pd.read_excel and if that fails, read it with pd.read_csv :那么为什么不假设它是一个 excel 文件,尝试使用pd.read_excel读取它,如果失败,请使用pd.read_csv读取它:

import pandas as pd
import sys
try:
    df = pd.read_excel(sys.argv[1])
    filetype = 'EXCEL'
except Exception:
    df = pd.read_csv(sys.argv[1])
    filetype = 'CSV'
print(filetype)

Try尝试

import os


ExcelFile = request.FILES['your_file_name']
ext = os.path.splitext(ExcelFile.name)[-1].lower()

print(ext)

Now You can compare the ext with .csv, .xls, .xlsx etc...现在您可以将 ext 与 .csv、.xls、.xlsx 等进行比较...

with if statement带 if 语句

if ext=='.xlsx':
    #do something

elif ext=='.xls':
    #do something

else:
    #The uploaded file is not the required format

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

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