如何在Python中检查上传的文件是CSV还是XLS?
如何检查上传的文件是CSV还是XLS。我想在Python中检查这个。我正在将一个文件导入到openerp中的一个二进制字段,这个字段可以作为二进制对象被提取。我需要读取这个文件并将数据导入到一个表格中。用户可以上传CSV或XLS文件。只有知道文件类型,我才能使用csv包或xlrd包。
3 个回答
4
你可以试试看,如果不行的话,就换个方法试试。
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."
5
这是对PolyWhirl帖子的一些补充,里面提到了一些我遇到的特殊情况。
def isExcelDoc(file):
excelSigs = [
('xlsx', b'\x50\x4B\x05\x06', 2, -22, 4),
('xls', b'\x09\x08\x10\x00\x00\x06\x05\x00', 0, 512, 8), #Saved from Excel
('xls', b'\x09\x08\x10\x00\x00\x06\x05\x00', 0, 1536, 8), #Saved from LibreOffice Calc
('xls', b'\x09\x08\x10\x00\x00\x06\x05\x00', 0, 2048, 8) #Saved from Excel then saved from Calc
]
for sigType, sig, whence, offset, size in excelSigs:
with open(file, 'rb') as f:
f.seek(offset, whence)
bytes = f.read(size)
if bytes == sig:
return True
return False
9
.xls 文件的十六进制签名如下:
这是Excel电子表格的子头信息(微软办公软件)
09 08 10 00 00 06 05 00 [512字节偏移]
你可以在维基百科上了解其他各种文件签名。
我认为你可以尝试这样做。虽然还没有测试过,但你可以自己动手试试,直到它有效为止。如果有任何建议或修改,欢迎留言。谢谢!
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
文件。
更新 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.