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

查看:904
本文介绍了如何在python中检查上传的文件是csv还是xls?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

推荐答案

.xls 文件如下:

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

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

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

更新1

对此进行了测试,我可以验证它是否可以检测.xls文件.

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

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)

这是输出:

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

这篇关于如何在python中检查上传的文件是csv还是xls?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆