如何检查上传的文件是python的csv或xls?

如何查看上传文件是CSV还是XLS 。 如何检查它在Python中。 我正在导入一个文件到openerp中的二进制字段,可以作为一个二进制对象。 我需要读取文件并将数据导入到表中。 用户可以上传csv或xls文件。 通过只知道我可以使用csv包或xlrd包。

.xls文件的hex签名如下所示:

Excel电子表格子标题(MS Office)

09 08 10 00 00 06 05 00 [512 byte offset]

您可以阅读维基百科上的其他各种签名。

我相信你可以做这样的事情。 这是未经testing的,但你可以摆弄它,直到它的工作。 对于任何build议或更改,请留下意见。 谢谢!

 xls_sig = b'\x09\x08\x10\x00\x00\x06\x05\x00' offset = 512 size = 8 with open('spreadsheet.xls', 'rb') as f: f.seek(offset) # Seek to the offset. bytes = f.read(size) # Capture the specified number of bytes. if bytes == xls_sig: print 'Uploaded file is an xls.' else: print 'File is not an xls.' 

更新1

经过testing,我可以validation它是否适用于检测.xls文件。

更新2

我开发了一个程序来确定文件是否是xls或xlsx:

 import codecs xlsx_sig = b'\x50\x4B\x05\06' xls_sig = b'\x09\x08\x10\x00\x00\x06\x05\x00' filenames = [ ('spreadsheet.xls', 0, 512, 8), ('spreadsheet.xlsx', 2, -22, 4)] for filename, whence, offset, size in filenames: with open(filename, 'rb') as f: f.seek(offset, whence) # Seek to the offset. bytes = f.read(size) # Capture the specified number of bytes. print codecs.getencoder('hex')(bytes) if bytes == xls_sig: msg = '"{}" is an xls.' elif bytes == xlsx_sig: msg = '"{}" is an xlsx.' else: msg = '"{}" is not an Excel document.' print msg.format(filename) 

这是输出:

 ('0908100000060500', 8) "spreadsheet.xls" is an xls. ('504b0506', 4) "spreadsheet.xlsx" is an xlsx. 

你可以尝试,如果不工作,尝试另一种方法。

 import xlrd import csv try: # reading the file by xlrd ... print "Thanks for your Excel file" except: # if you find specific Exception types, use them here try: # reading as CSV file ... print "thanks for your CSV file" except: # if you find specific Exception types, use them here print "sorry, now way, give me some usable file."