473,513 Members | 7,598 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Parse file into array

I was wondering how i could parse the contents of a file into an array.
the file would look something like this:

gif:image/gif
html:text/html
jpg:image/jpeg
....

As you can see, it contains the mime type and the file extension
seperated by commas, 1 per line. I was wondering if it was possible to
create and array like this:

(Pseudocode)
mimetypearray[gif] = "image/gif"
mimetypearray[html] = "text/html"
mimetypearray[jpg] = "image/jpeg"
....

I come from a PHP backround where I know this is possible, but I am new
at Python. Please disregard this if it is a stupid question.

Nov 22 '05 #1
7 3287
> I was wondering how i could parse the contents of a file into an array.
the file would look something like this:

gif:image/gif
html:text/html
jpg:image/jpeg


Try something like this:

d = {}
for line in open("input.txt").readlines():
ext, mime = line.strip().split(":")
d[ext] = mime
print d

Craig
Nov 22 '05 #2
amfr wrote:
I was wondering how i could parse the contents of a file into an array.
the file would look something like this:

gif:image/gif
html:text/html
jpg:image/jpeg
...

As you can see, it contains the mime type and the file extension
seperated by commas, 1 per line. I was wondering if it was possible to
create and array like this:

(Pseudocode)
mimetypearray[gif] = "image/gif"
mimetypearray[html] = "text/html"
mimetypearray[jpg] = "image/jpeg"
...


You want a dictionary, not an array.

mimetypedict = {}
for line in mimetypefile:
line = line.rsplit('\r\n')
extension, mimetype = line.split(':')
mimetypedict[extension] = mimetype

Note that there's already a MIME type database in the standard mimtypes
module: <http://python.org/doc/current/lib/module-mimetypes.html>.
Nov 22 '05 #3
Thanks a lot. The webserver I am writing works now :)

Nov 22 '05 #4
Leif K-Brooks wrote:
line = line.rsplit('\r\n')

Er, that should be line.rstrip, not line.rsplit.
Nov 22 '05 #5
If it helps, there's a builtin module for figuring out mimetypes;

http://docs.python.org/lib/module-mimetypes.html
import mimetypes
mimetypes.guess_type('.gif')

('image/gif', None)
Cheers,

Andy.

Nov 22 '05 #6
On 14 Nov 2005 13:48:45 -0800, "amfr" <am******@gmail.com> wrote:
I was wondering how i could parse the contents of a file into an array.
the file would look something like this:

gif:image/gif
html:text/html
jpg:image/jpeg
...

As you can see, it contains the mime type and the file extension
seperated by commas, 1 per line. I was wondering if it was possible to
create and array like this:

(Pseudocode)
mimetypearray[gif] = "image/gif"
mimetypearray[html] = "text/html"
mimetypearray[jpg] = "image/jpeg"
...

I come from a PHP backround where I know this is possible, but I am new
at Python. Please disregard this if it is a stupid question.

Pretty much anything is possible in Python, if you can conceive it well enough ;-)

Assuming f is from f = open(yourfile), simulated with StringIO file object here,
from StringIO import StringIO
f = StringIO("""\ ... gif:image/gif
... html:text/html
... jpg:image/jpeg
... """)

And assuming that there are no spaces around the ':' or in the two pieces,
but maybe some optional whitespace at either end of a line and \n at the end
(except maybe the last line), and no blank lines, you can get a dict mapping easily:
mimetypedict = dict(tuple(line.strip().split(':')) for line in f)
This gives you: mimetypedict {'gif': 'image/gif', 'html': 'text/html', 'jpg': 'image/jpeg'}

Which you can access using the names as keys, e.g., mimetypedict['gif'] 'image/gif'

If you want to use bare names to access the info via an object, you can use the
dict info to create a class or class instance and give it the named attributes, e.g.
a class with the data as class variables is quick:
MTC = type('MTC',(), mimetypedict)
MTC.gif 'image/gif' MTC.jpg

'image/jpeg'

Or you could substitute the mimetypedict expression from above to make another one-liner ;-)

Other ways of setting up your info are certainly possible, and may be more suitable,
depending on how you intend to use the info. As mentioned, the mimetypes module
may already have much of the data and/or functionality you want.

Regards,
Bengt Richter
Nov 22 '05 #7
On 14 Nov 2005 13:48:45 -0800, "amfr" <am******@gmail.com> wrote:
I was wondering how i could parse the contents of a file into an array.
the file would look something like this:

gif:image/gif
html:text/html
jpg:image/jpeg
...

As you can see, it contains the mime type and the file extension
seperated by commas, 1 per line. I was wondering if it was possible to
create and array like this:

(Pseudocode)
mimetypearray[gif] = "image/gif"
mimetypearray[html] = "text/html"
mimetypearray[jpg] = "image/jpeg"
...

I come from a PHP backround where I know this is possible, but I am new
at Python. Please disregard this if it is a stupid question.

Pretty much anything is possible in Python, if you can conceive it well enough ;-)

Assuming f is from f = open(yourfile), simulated with StringIO file object here,
from StringIO import StringIO
f = StringIO("""\ ... gif:image/gif
... html:text/html
... jpg:image/jpeg
... """)

And assuming that there are no spaces around the ':' or in the two pieces,
but maybe some optional whitespace at either end of a line and \n at the end
(except maybe the last line), and no blank lines, you can get a dict mapping easily:
mimetypedict = dict(tuple(line.strip().split(':')) for line in f)
This gives you: mimetypedict {'gif': 'image/gif', 'html': 'text/html', 'jpg': 'image/jpeg'}

Which you can access using the names as keys, e.g., mimetypedict['gif'] 'image/gif'

If you want to use bare names to access the info via an object, you can use the
dict info to create a class or class instance and give it the named attributes, e.g.
a class with the data as class variables is quick:
MTC = type('MTC',(), mimetypedict)
MTC.gif 'image/gif' MTC.jpg

'image/jpeg'

Or you could substitute the mimetypedict expression from above to make another one-liner ;-)

Other ways of setting up your info are certainly possible, and may be more suitable,
depending on how you intend to use the info. As mentioned, the mimetypes module
may already have much of the data and/or functionality you want.

Regards,
Bengt Richter
Nov 22 '05 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
12065
by: Tyaan | last post by:
Hi.. I'm a perl noob need to know how to write a script to parse a file containing one to four of the following blocks of text? I then want to print the results in a format showing the memory size...
2
10667
by: iop | last post by:
Hello there, I'd like to "parse" an entire multi-dimension array like this : APP APP without knowing "framework" or "config" or anything passed as variables... 'cause it's simple to call...
23
2549
by: Charles Law | last post by:
Does anyone have a regex pattern to parse HTML from a stream? I have a well structured file, where each line is of the form <sometag someattribute='attr'>text</sometag> for example <SPAN...
24
3128
by: | last post by:
Hi, I need to read a big CSV file, where different fields should be converted to different types, such as int, double, datetime, SqlMoney, etc. I have an array, which describes the fields and...
19
3203
by: Johnny Google | last post by:
Here is an example of the type of data from a file I will have: Apple,4322,3435,4653,6543,4652 Banana,6934,5423,6753,6531 Carrot,3454,4534,3434,1111,9120,5453 Cheese,4411,5522,6622,6641 The...
5
64582
AdrianH
by: AdrianH | last post by:
Assumptions I am assuming that you know or are capable of looking up the functions I am to describe here and have some remedial understanding of C++ programming. FYI Although I have called...
3
1536
by: cmdolcet69 | last post by:
How do i parse a text file with data value in it? I have a series of values that are sepereated by commas. the file holds around 3700 values and all these values need to be parsed out and put into...
3
1697
by: Bint | last post by:
Hi, I'm trying to parse an xml file into an array tree. From the PHP site in the comments, I got this code. But it doesn't work for me. It's saying that the passed variable is not an array or...
0
7153
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
7373
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
1
7094
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
7519
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
1
5079
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
3230
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
3218
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
1585
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...
1
796
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.