[Tutor] wheel.py

Magnus Lycka magnus@thinkware.se
Sat, 28 Sep 2002 22:55:26 +0200


I'm taking the liberty to reinvent your wheel! ;)

Since you are rewriting your file on every run
to store your index number, you might as well swap
the lines around instead. Always read from the top
and place that line last when you are done. Skip
the number.

(Beware, untested code follows)

----
fileName=sys.argv[1]

f=open(fileName,'rt'),
textList=f.readlines()
f.close()

firstLine = textList.pop(0)
print firstLine.strip()
textList.append(firstLine)

f=open(file,'wt')
f.writelines(textList)
f.close()
----

If the text file is big, it might be better
to keep the index in a separate file and
use your indexing scheme. Both files are
now given as arguments. (Another option
would be to have myfile.txt and myfile.ix
etc.)

BTW, the official way to open a file is now
"file()". (See library reference.)

----
indexFileName, dataFileName=sys.argv[1:3]

# To make sure this works in Jython we must explicitly
# close the file we'll later open for writing.
# In CPython we could write it more compact as
# index = int(file(indexFileName, 'rt').read())
ixFile = file(indexFileName, 'rt')
index = int(ixFile.read())
ixFile.close()

text = file(dataFileName, 'rt').readlines()

try:
     print text[index].strip()
     index += 1
except IndexError:
     print text[0].strip()
     index = 1

ixFile = file(indexFileName, 'wt')
ixFile.write(str(index))
ixFile.close()
----

Finally, if the file is very big, we don't want to read
in more than we have to...

----
indexFileName, dataFileName=sys.argv[1:3]

ixFile = file(indexFileName, 'rt')
index = int(ixFile.read())
ixFile.close()

i = 0
for line in file(dataFileName, 'rt'):
     if i == 0: lineZero = line
     if i == index:
         print line.strip()
         index += 1
         break
     i += 1
else:
     print lineZero.strip()
     index = 1

ixFile = file(indexFileName, 'wt')
ixFile.write(str(index))
ixFile.close()
----

If it's even bigger...we'll use a database of some
sort. import anydbm etc... Another day...


-- 
Magnus Lycka, Thinkware AB
Alvans vag 99, SE-907 50 UMEA, SWEDEN
phone: int+46 70 582 80 65, fax: int+46 70 612 80 65
http://www.thinkware.se/  mailto:magnus@thinkware.se