Reputation: 47
I receive some data as a string. I need to write the data to a file, but the problem is that sometimes the data is compressed/zipped and sometimes it's just plain text. I need to determine the content-type so I know whether to write it to a .txt file or a .tgz file. Any ideas on how to accomplish this? Can I use mime type somehow even though my data is a string, not a file?
Thanks.
Upvotes: 2
Views: 2650
Reputation: 188114
As some answers already suggested, you could peek into the first bytes of the file:
#!/usr/bin/env python
# $ cat hello.txt
# Hello World. I'm plaintext.
# $ cat hello.txt | gzip > hello.txt.gz
from struct import unpack
# 1F 8B 08 00 / gz magic number
magic = ('\x1f', '\x8b', '\x08', '\x00')
for filename in ['hello.txt', 'hello.txt.gz']:
with open(filename, 'rb') as handle:
s = unpack('cccc', handle.read(4))
if s == magic:
print filename, 'seems gzipped'
else:
print filename, 'seems not gzipped'
# =>
# hello.txt seems not gzipped
# hello.txt.gz seems gzipped
Upvotes: 1
Reputation: 40894
Both gzip and zip use distinct headers before compressed data, rather unlikely for human-readable strings. If the choice is only between these, you can make a faster check than mimetypes
would provide.
Upvotes: 1
Reputation: 304355
If the file is downloaded from a webserver, you should have a content-type to look at, however you are at the mercy of the webserver whether or not it truly describes the type of the file.
Another alternative would be to use a heuristic to guess the file type. This can often be done by looking at the first few bytes of the file
Upvotes: 1
Reputation: 298364
You can try the mimetypes
module: http://docs.python.org/library/mimetypes.html.
Here's something to play with:
print mimetypes.guess_type(filename)
Good luck!
Upvotes: 0