python判断文件类型是不是excel_如何在python中检查上传的文件是csv还是xls?

How to check is upload file is CSV or XLS .

How to check it in python. I'm importing a file to a binary field in openerp which can be retrived as a binary object. I need to read the file and import the data to a table. User can upload csv or xls file. By knowing only I can use the csv package or xlrd package.

解决方案

The hex signature for an .xls file is the following:

Excel spreadsheet subheader (MS Office)

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

You can read about the other various signatures on Wikipedia.

I believe that you can do something like this. This is untested, but you can fiddle around with it until it works. Please leave comments for any suggestions or changes. Thanks!

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

Update 1

Tested this and I can verify that it works for detecting .xls files.

Update 2

I developed a program to determine if the file is an xls or 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)

Here is the output:

('0908100000060500', 8)

"spreadsheet.xls" is an xls.

('504b0506', 4)

"spreadsheet.xlsx" is an xlsx.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值