如何确定数据是否是有效的没有文件的tar文件? [英] How to determine if data is valid tar file without a file?
问题描述
我的上传表单需要一个tar文件,我想检查上传的数据是否有效. tarfile 模块支持
My upload form expects a tar file and I want to check whether the uploaded data is valid. The tarfile module supports is_tarfile()
, but expects a filename - I don't want to waste resources writing the file to disk just to check if it is valid.
是否可以使用标准Python库检查数据是否为有效的tar文件而无需写入磁盘?
Is there a way to check the data is a valid tar file without writing to disk, using standard Python libraries?
推荐答案
说您上传的数据包含在字符串data
中.
Say your uploaded data is contained in string data
.
from tarfile import TarFile, TarError
from StringIO import StringIO
sio = StringIO(data)
try:
tf = TarFile(fileobj=sio)
# process the file....
except TarError:
print "Not a tar file"
还有其他复杂性,例如处理不同的tar文件格式和压缩. tarfile 文档中提供了更多信息.
There are additional complexities such as handling different tar file formats and compression. More info is available in the tarfile documentation.
这篇关于如何确定数据是否是有效的没有文件的tar文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!