473,788 Members | 2,898 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

reading files into dicts

rbt
What's a good way to write a dictionary out to a file so that it can be
easily read back into a dict later? I've used realines() to read text
files into lists... how can I do the same thing with dicts? Here's some
sample output that I'd like to write to file and then read back into a dict:

{'.\\sync_pics. py': 1135900993, '.\\file_histor y.txt': 1135900994,
'.\\New Text Document.txt': 1135900552}
Dec 30 '05 #1
9 1633
rbt wrote:
What's a good way to write a dictionary out to a file so that it can
be easily read back into a dict later? I've used realines() to read
text
files into lists... how can I do the same thing with dicts? Here's
some sample output that I'd like to write to file and then read back
into a dict:

{'.\\sync_pics. py': 1135900993, '.\\file_histor y.txt': 1135900994,
'.\\New Text Document.txt': 1135900552}

d = {'.\\sync_pics. py': 1135900993, '.\\file_histor y.txt': 1135900994, .... '.\\New Text Document.txt': 1135900552} file("foo", "w").write(repr (d))
data = file("foo").rea d()
data "{'.\\\\sync_pi cs.py': 1135900993, '.\\\\file_hist ory.txt': 1135900994,
'.\\\\New Text Document.txt': 1135900552}" d = eval(data)
d

{'.\\sync_pics. py': 1135900993, '.\\file_histor y.txt': 1135900994, '.\\New Text
Document.txt': 1135900552}

--
Giovanni Bajo
Dec 30 '05 #2
2005/12/30, rbt <rb*@athop1.ath .vt.edu>:
What's a good way to write a dictionary out to a file so that it can be
easily read back into a dict later? I've used realines() to read text
files into lists... how can I do the same thing with dicts? Here's some
sample output that I'd like to write to file and then read back into a dict:

{'.\\sync_pics. py': 1135900993, '.\\file_histor y.txt': 1135900994,
'.\\New Text Document.txt': 1135900552}
--
http://mail.python.org/mailman/listinfo/python-list


You can try the dict4ini module written by me.

http://wiki.woodpecker.org.cn/moin/Dict4Ini

The dict can be saved as an Ini file, and can be read back from the
Ini file.Just like:
import dict4ini
x = {'.\\sync_pics. py': 1135900993, '.\\file_histor y.txt': 1135900994, '.\\New Text Document.txt': 1135900552} d = dict4ini.DictIn i(values=x)
d['.\sync_pics.py ']

1135900993

--
I like python!
My Blog: http://www.donews.net/limodou
NewEdit Maillist: http://groups.google.com/group/NewEdit
Dec 30 '05 #3
rbt wrote:
What's a good way to write a dictionary out to a file so that it can be
easily read back into a dict later? I've used realines() to read text
files into lists... how can I do the same thing with dicts? Here's some
sample output that I'd like to write to file and then read back into a dict:

{'.\\sync_pics .py': 1135900993, '.\\file_histor y.txt': 1135900994,
'.\\New Text Document.txt': 1135900552}

A better way, than rolling your own marshaling (as this is called),
would be to use the cPickle module. It can write almost any Python
object to a file, and then read it back in later. It's more efficient,
and way more general than any code you're likely to write yourself.

The contents of the file are quite opaque to anything except the cPickle
and pickle modules. If you *do* want to roll you own input and output to
the file, the standard lib functions "repr" and "eval" can be used. Repr
is meant to write out objects so they can be read back in and recovered
with eval. If the contents of your dictionary are well behaved enough
(simple Python objects are, and classes you create may be made so), then
you may be able to get away with as little as this:

f = file('file.name ', 'wb')
f.write(repr(my Dictionary))
f.close()

and

f = file('file.name ', 'rb')
myDictionary = eval(f.read())
f.close()

Simple as that is, I'd still recommend the cPickle module.

As always, this security warning applys: Evaluating arbitrary text
allows anyone, who can change that text, to take over complete control
of your program. So be carefully.

Gary Herron
Dec 30 '05 #4
A further thought, if you write the data to a file in the correct
format, you can use import and reload to access the data later instead
of repr.

On 12/29/05, Tim Williams (gmail) <td*******@gmai l.com> wrote:
On 30/12/05, Giovanni Bajo <no***@sorry.co m> wrote:

>> d = {'.\\sync_pics. py': 1135900993, '.\\file_histor y.txt':

1135900994,
.... '.\\New Text Document.txt': 1135900552}
>> file("foo", "w").write(repr (d))
>> data = file("foo").rea d()
>> data

"{'.\\\\sync_pi cs.py': 1135900993, '.\\\\file_hist ory.txt': 1135900994,
'.\\\\New Text Document.txt': 1135900552}"
>> d = eval(data)
>> d

{'.\\sync_pics. py': 1135900993, '.\\file_histor y.txt': 1135900994,

'.\\New
Text
Document.txt': 1135900552}

eval() is risky if you can't control the contents of the file :)


--

Tim Williams
Dec 30 '05 #5
Apologies for the top post, it was my first attempt at using gmail's
pda-enabled web interface. There is no option to bottom post.

Apart from the mistake in my previous reply, when I meant to suggest
using import instead of eval() not repr(). I also omitted an example.
So here goes -but I don't know how gmail-CE will format this!!

Save your dict to a file with a .PY extension using

outdata = 'mydict =' + repr(dict) # or somesuch
similar

dictfile.py
-----------------------
mydict = {'key1':'a', 'key2':'b'}
-----------------------

Then:

import dictfile
print dictfile.mydict .keys()
['key1','key2']

reload(dictfile )

HTH :-)

--

Tim Williams
Dec 30 '05 #6
rbt
Gary Herron wrote:
rbt wrote:
What's a good way to write a dictionary out to a file so that it can
be easily read back into a dict later? I've used realines() to read
text files into lists... how can I do the same thing with dicts?
Here's some sample output that I'd like to write to file and then read
back into a dict:

{'.\\sync_pics. py': 1135900993, '.\\file_histor y.txt': 1135900994,
'.\\New Text Document.txt': 1135900552}

A better way, than rolling your own marshaling (as this is called),
would be to use the cPickle module. It can write almost any Python
object to a file, and then read it back in later. It's more efficient,
and way more general than any code you're likely to write yourself.

The contents of the file are quite opaque to anything except the cPickle
and pickle modules. If you *do* want to roll you own input and output to
the file, the standard lib functions "repr" and "eval" can be used. Repr
is meant to write out objects so they can be read back in and recovered
with eval. If the contents of your dictionary are well behaved enough
(simple Python objects are, and classes you create may be made so), then
you may be able to get away with as little as this:

f = file('file.name ', 'wb')
f.write(repr(my Dictionary))
f.close()

and

f = file('file.name ', 'rb')
myDictionary = eval(f.read())
f.close()

Simple as that is, I'd still recommend the cPickle module.

As always, this security warning applys: Evaluating arbitrary text
allows anyone, who can change that text, to take over complete control
of your program. So be carefully.

Gary Herron


Thanks to everyone for the tips on eval and repr. I went with the
cPickle suggestion... this is awesome! It was the easiest and quickest
solution performance-wise. Just makes me think, "Wow... how the heck
does pickle do that?!"

Thanks again,
rbt
Dec 30 '05 #7
On 2005-12-30, Tim Williams (gmail) wrote:
Apologies for the top post, it was my first attempt at using gmail's
pda-enabled web interface. There is no option to bottom post.


Can you not move the cursor?

--
Chris F.A. Johnson, author | <http://cfaj.freeshell. org>
Shell Scripting Recipes: | My code in this post, if any,
A Problem-Solution Approach | is released under the
2005, Apress | GNU General Public Licence
Dec 30 '05 #8
ConfigObj is good - it (effectively) turns a dictionary into an ini
file, and vice versa.

There is also built in support for type conversion.

See http://www.voidspace.org.uk/python/configobj.html

See the ConfigPersist module which has functions to use ConfigObj for
data persistence. It explains the limitations.

http://www.voidspace.org.uk/python/configpersist.html

Basically you can store and retrieve dictionaries, lists, strings,
integers, floats and booleans. You can nest dictionaries - but you
can't nest dictionaries in lists. All the keys must be strings - but
the module/article suggests a way round that, at the expense of
readability of the resulting text file.

All the best,

Fuzzyman
http://www.voidspace.org.uk/python/index.shtml

Dec 30 '05 #9
rbt <rb*@athop1.ath .vt.edu> wrote:
...
Thanks to everyone for the tips on eval and repr. I went with the
cPickle suggestion... this is awesome! It was the easiest and quickest
solution performance-wise. Just makes me think, "Wow... how the heck
does pickle do that?!"


pickle.py implements just the same job, in pure Python, and it's easily
found within your Python's standard library, so you may want to study it
to see how it does perform its task.
Alex
Jan 2 '06 #10

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

Similar topics

12
9007
by: Afanasiy | last post by:
I have some code like this... self.write( ''' lots of stuff here with %(these)s named expressions ''' % vars(self) ) Then I wanted to add an item to the dict vars(self), so I tried :
2
2207
by: Jerry | last post by:
My "main" class is getting a bit long...Is it possble to split a class definition into several files and then import the pieces to get the whole definition? Jerry
14
1538
by: Klaus Neuner | last post by:
Hello, I need to gather information that is contained in various files. Like so: file1: ===================== foo : 1 2 bar : 2 4
2
3253
by: nnimod | last post by:
Hi. I'm having trouble reading some unicode files. Basically, I have to parse certain files. Some of those files are being input in Japanese, Chinese etc. The easiest way, I figured, to distinguish between plain ASCII files I receive and the Unicode ones would be to check if the first two bytes read 0xFFFE. But nothing I do seems to be able to do that. I tried reading it in binary mode and reading two characters in:
12
1432
by: Guyon Morée | last post by:
Hi all, I'm using simple classes as a container of named values and I'm instantiating a lot of them in a very short time. i was wondering if there is any benefit in using dicts instead from a performance/memory usage point of view? regards,
6
1838
by: bearophileHUGS | last post by:
I have found that in certain situations ordered dicts are useful. I use an Odict class written in Python by ROwen that I have improved and updated some for personal use. So I'm thinking about a possible C version of Odict (maybe fit for the collections module). On a 32 bit Win Python 2.5 requires about: 28.2 bytes/element for set(int) 36.2 bytes/element for dict(int:None)
10
8358
by: Tyler | last post by:
Hello All: After trying to find an open source alternative to Matlab (or IDL), I am currently getting acquainted with Python and, in particular SciPy, NumPy, and Matplotlib. While I await the delivery of Travis Oliphant's NumPy manual, I have a quick question (hopefully) regarding how to read in Fortran written data. The data files are not binary, but ASCII text files with no formatting and mixed data types (strings, integers,...
12
1879
by: Alan Isaac | last post by:
This discussion ended abruptly, and I'd like to see it reach a conclusion. I will attempt to synthesize Bill and Carsten's proposals. There are two proposed patches. The first is to http://docs.python.org/lib/typesmapping.html where it is proposed for footnote (3) to state: Keys and values are listed in an arbitrary order. This order is indeterminate and generally depends on factors outside the scope
0
990
by: Chris Rebert | last post by:
On Thu, Oct 16, 2008 at 12:19 PM, John Townsend <jtownsen@adobe.comwrote: Right, this clobbers the existing entry with this new blank one. This is evidenced by the fact that you're performing an _assignment_ on a dictionary key rather than calling a _mutator_ method on a dictionary value. A dictionary has only one value for a given key (but importantly, that value can be a list). Switch to a Dict of Lists of Dicts and append to the...
0
9656
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10364
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10172
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8993
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7517
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 presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6750
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5398
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 last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5536
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3670
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.