473,789 Members | 2,833 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Problem with loading textfiles into dictionaries.

Hello,
I want to do the following:

def do_load(self, arg):
sitefile = file('sitelist' , 'r+', 1)
while True:
siteline = sitefile.readli ne()
site_rawlist = siteline.split( )
sitelist[site_rawlist[0]] = site_rawlist[1:]
if len(siteline) == 0:
break

I want to load a textfile into a dictionaries and use the first word on
a line as the key for the list, then take the remaining words of the
line and make them values of the key. This doesn't work:

File "ftp.py", line 57, in do_load
sitelist[site_rawlist[0]] = site_rawlist[1:]
IndexError: list index out of range

However, it works flawlessy in another function, where I have:

def do_add(self, arg):
sitefile = file('sitelist' , 'r+', 1)
act_addlist = arg.split()
sitelist[act_addlist[0]] = act_addlist[1:]
sitefile.seek(0 ,2)
sitefile.write( arg + "\n")
print "Written to database."

Anyone knows why it doesn't work in the first function? Help very much
appreciated.

munin

Jul 18 '05 #1
6 1346
On 30 Jan 2005 16:43:26 -0800, me*********@gma il.com
<me*********@gm ail.com> wrote:
Hello,
I want to do the following:

def do_load(self, arg):
sitefile = file('sitelist' , 'r+', 1)
while True:
siteline = sitefile.readli ne()
site_rawlist = siteline.split( )
sitelist[site_rawlist[0]] = site_rawlist[1:]
if len(siteline) == 0:
break


maybe you would be better off doing something slightly simpler, and in
such a way that you see the input which is causing problems.

sitelist = {}
for line in file('sitelist' ):
elems = line.split()
if len(elems) == 1:
raise ValueError, "Invalid line in file %r" % line
sitelist[elem[0]] = elem[1:]

:)

Stephen
Jul 18 '05 #2
mercuryp...@gma il.com wrote:
Hello,
I want to do the following:

def do_load(self, arg):
sitefile = file('sitelist' , 'r+', 1)
while True:
siteline = sitefile.readli ne()
site_rawlist = siteline.split( )
sitelist[site_rawlist[0]] = site_rawlist[1:]
if len(siteline) == 0:
break

I want to load a textfile into a dictionaries and use the first word on a line as the key for the list, then take the remaining words of the
line and make them values of the key. This doesn't work:

File "ftp.py", line 57, in do_load
sitelist[site_rawlist[0]] = site_rawlist[1:]
IndexError: list index out of range


Hello again Munin,
First i'll start with a spanking!
Post your code like this:(or pick your favorite starter)
Py> def do_load(self, arg):
.... sitefile = file('sitelist' , 'r+', 1)
.... while True:
.... siteline = sitefile.readli ne()
.... site_rawlist = siteline.split( )
.... sitelist[site_rawlist[0]] = site_rawlist[1:]
.... if len(siteline) == 0:
.... break
See how much nicer that is even if the newsfeed gets mangled it comes
out ok(mostly).
If I guess right it looks like you are trying disect a line that was
empty or only had one element.
If you check for line length first you might do better.
Py> def do_load(self, arg):
.... sitefile = file('sitelist' , 'r+', 1)
.... while True:
.... if len(siteline) == 0:
.... break
.... siteline = sitefile.readli ne()
.... site_rawlist = siteline.split( )
.... sitelist[site_rawlist[0]] = site_rawlist[1:]

Ok next thing is this smells like you really are trying to reinvent a
sort of pickle.
If you don't know search for 'python pickle module'.
examples abound but here it is anyway:
Py> import pickle
Py> # Pickle a dictionary
Py> f = open('/tmp/mydata', 'wb')
Py> f.write(pickle. dumps(yourdict)
Py> f.close()
Py> # and it is easy to get back as well
Py> f = open('tmp/mydata', rb')
Py> pdata = f.read()
Py> f.close()
Py> yourdict = pickle.load(pda ta)
hth,
M.E.Farmer

Jul 18 '05 #3
me*********@gma il.com said the following on 1/30/2005 7:43 PM:
Hello,
I want to do the following:

def do_load(self, arg):
sitefile = file('sitelist' , 'r+', 1)
while True:
siteline = sitefile.readli ne()
site_rawlist = siteline.split( )
sitelist[site_rawlist[0]] = site_rawlist[1:]
if len(siteline) == 0:
break

I want to load a textfile into a dictionaries and use the first word on
a line as the key for the list, then take the remaining words of the
line and make them values of the key. This doesn't work:

File "ftp.py", line 57, in do_load
sitelist[site_rawlist[0]] = site_rawlist[1:]
IndexError: list index out of range


Hi - It looks like your code encountered a blank line when you got this
error.

You should move "if len(siteline) == 0" part right after your readline.
The way you have done it really does not help.

def do_load(self, arg):
sitefile = file('sitelist' , 'r+', 1)
while True:
siteline = sitefile.readli ne()
if len(siteline) == 0:
break
site_rawlist = siteline.split( )
sitelist[site_rawlist[0]] = site_rawlist[1:]

Thanks,
--Kartic
Jul 18 '05 #4
Kartic said the following on 1/30/2005 8:21 PM:
me*********@gma il.com said the following on 1/30/2005 7:43 PM: Hi - It looks like your code encountered a blank line when you got this
error.

You should move "if len(siteline) == 0" part right after your readline.
The way you have done it really does not help.

def do_load(self, arg):
sitefile = file('sitelist' , 'r+', 1)
while True:
siteline = sitefile.readli ne()
if len(siteline) == 0:
break
site_rawlist = siteline.split( )
sitelist[site_rawlist[0]] = site_rawlist[1:]

Sorry...sitelin e = sitefile.readli ne().strip()
Jul 18 '05 #5
Yeah I kind of want to 'reinvent' the pickle and I am aware of that.
The problem for me is that the output that pickle dumps to a file is
too 'cryptic' as I want the ability to edit the corresponding textfile
directly and easily, so I'm going for an own way.

But yes, Kartic and you were basically right about the line length and
checking it first. Didn't really think about it, maybe I was too
tired... :) Thanks again! Hope I'm not bothering you all with my
extremely newbie questions.

munin

Jul 18 '05 #6
Kartic wrote:
me*********@gma il.com said the following on 1/30/2005 7:43 PM:
Hello,
I want to do the following:

def do_load(self, arg):
sitefile = file('sitelist' , 'r+', 1)
while True:
siteline = sitefile.readli ne()
site_rawlist = siteline.split( )
sitelist[site_rawlist[0]] = site_rawlist[1:]
if len(siteline) == 0:
break

You should move "if len(siteline) == 0" part right after your readline.
The way you have done it really does not help.


Or better yet, don't use "if len(siteline) == 0" -- use "if siteline".
See this an other examples of dubious Python:

http://www.python.org/moin/DubiousPython

Specifically, see the section on Overly Verbose Conditionals.

Steve
Jul 18 '05 #7

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

Similar topics

3
2377
by: Shivram U | last post by:
Hi, I want to store dictionaries on disk. I had a look at a few modules like bsddb, shelve etc. However would it be possible for me to do the following hash = where the key is an int and not a string bsddb requires that both the key,value are string. shelve does support values being object but not the keys. Is there any
4
4735
by: Jorgen Gustafsson | last post by:
Hi, im trying to write a small progam to compare data in 2 textfiles. I want to search for values that doesnt exist in File2. The result should be "3" in the example below but Im not able to do this since my program crosschecks all numbers in both files and Im getting a lot of "hits". (outer and inner while-loops) Below is an examples of the textfiles:
4
1703
by: Paul Bromley | last post by:
I thought that XMLTextReader would be simple to use, but I have run into problems with it! I seem to have great difficulty extrcting the text of specific elements from a very simple XML file. I have a very simple XML file that I wish to parse using Xmltextreader, but I seem to be having a lot of poblems with it. I have a subroutine that I pass a string into, and what I need to do is to find the element where that string exists, and then...
210
10560
by: Christoph Zwerschke | last post by:
This is probably a FAQ, but I dare to ask it nevertheless since I haven't found a satisfying answer yet: Why isn't there an "ordered dictionary" class at least in the standard list? Time and again I am missing that feature. Maybe there is something wrong with my programming style, but I rather think it is generally useful. I fully agree with the following posting where somebody complains why so very basic and useful things are not part...
8
1750
by: placid | last post by:
Hi all, Just wondering if anyone knows how to pop up the dialog that windows pops up when copying/moving/deleting files from one directory to another, in python ? Cheers
3
1023
by: Jarry | last post by:
I have two arrays to load, taking one line to an entry from two 770,000 line files: so I have two arrays of 770000. But this can take upwards of 5 minutes, which is simply too long. I use a stream reader to readline from the textfiles, using the syntax For i = 1 to 770000 myArray(i) = myStreamReader.readLine() Next How can I speed this process up, but try to keep the arrays that size? All ideas welcomed.
1
165
by: Edwin.Madari | last post by:
by the way, iterating over bar will throw KeyError if that key does not exist in foo. to see that in action, simply set another key in bar after copy.deepcopy stmt in this example.. bar = 0 and re-run.... fun learning with python... Edwin -----Original Message----- From: Madari, Edwin Sent: Thursday, August 14, 2008 9:24 PM
14
1824
by: cnb | last post by:
Are dictionaries the same as hashtables?
1
11762
by: blackirish | last post by:
Hi all, I am writing a WPF application which uses styles to visualize controls in the application. I use separate resource dictionaries. ControlTemplates.xaml, Animations.xaml and a folder named Colors including different resource dictionaries to change the control colors on the fly. I am using MergedDictionaries to load styles such that; Then i get an exception when loading resources like; "A first chance exception of type...
0
9666
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
9511
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10410
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...
1
10139
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9020
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
7529
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
6769
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();...
2
3701
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2909
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.