newbie: Some file object tips?

Gerhard =?unknown-8bit?Q?H=E4ring?= gh_pythonlist at gmx.de
Tue Feb 19 07:07:46 EST 2002


Le 19/02/02 ? 11:00, Flavian Hardcastle écrivit:
> 
> I'm writing a crude cgi chat script. I've already got it up and working 
> with Xitami server, and have chatted with a few net buddies.
> 
> How it works is very rough and simple... it basically just takes data from 
> people's browsers (using the FieldStorage function) and stores it in a file 
> called log.txt, and then displays the contents of that file back to them.
> 
> My problem is ... 
> 
> The longer you chat, the bigger the log.txt file gets, and consequently the 
> web page the chatters are viewing gets bigger and bigger, and becomes hard 
> to download.
> 
> So I want to include a "scroll back" feature ... which will enable the user 
> to control how many previous posts (s)he views. It will probably take the 
> form a simple input box on the form ... if you want to see the last 8 
> posts, you put 8 in the box, if you want to see the last 50 posts, you put 
> 50 in the box and so on.
> 
> So, I need the script to be able to search the log.txt file. Any tips as to 
> how I might go about this? 

You could read the file into a list with

lines = open("log.txt").readlines()

but now, all the lines will include a newline character at their end. To
strip these, you can do the following instead:

lines = map(string.rstrip, open("log.txt").readlines())

Now you can use slicing on the list, say to return the last 8 lines, you
can do:

lines[-8:]

HTH,

Gerhard
-- 
This sig powered by Python!
Außentemperatur in München: 4.8 °C      Wind: 6.1 m/s




More information about the Python-list mailing list