-1

My problem statement is to find if the imported file is a CSV or EXCEL file in pandas. The input will be given from the command line as sys.argv[1] where sys.argv[1] is '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

eg: python myscript.py D:/Users/abc [abc is the file name]

This should say if the file is CSV or 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?

Any help would be highly appreciated

Malathy
  • 63
  • 7
  • Possible duplicate of [Checking file extension](https://stackoverflow.com/questions/5899497/checking-file-extension) – shaik moeed May 29 '19 at 11:42
  • 1
    You have to describe your problem better here. What is exactly going wrong? Try to add an example so people can see what is going wrong – Erfan May 29 '19 at 11:42

2 Answers2

0

Since you give the filename "abc" as an example, I assume that you cannot decide on the file type based on extension. 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:

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)
Rob
  • 3,418
  • 1
  • 19
  • 27
0

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...

with if statement

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

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

else:
    #The uploaded file is not the required format
Merrin K
  • 1,602
  • 1
  • 16
  • 27