looping through a file

Bengt Richter bokr at oz.net
Fri Jul 25 20:09:28 EDT 2003


On Fri, 25 Jul 2003 22:29:15 +0200, Adam <efkw at fawekm.com> wrote:

>Psybar Phreak wrote:
   (Sorry, your original post seems out of sight, so I'm answering this one)

>> hi all - ive just started with python (after having done java and c) and am
>> having a little bit of trouble with the script.  Im using as a login script.
>> 
>> There's a users.dat file in the format
>> user1
>> user1password
>> user2
>> user2password
>> ... etc
>> 
>> at the moment - the code i work, only checks the first and second lines (ie.
>> details of user1).  but it appears that python doesn't have a do... while...
>> until loop.
>> 
>> 
>> can anyone help?
>> 
>> thanks!!
>> 
>> Ive attached the appropriate part of the code i have working
>> 
>> -------------------------------
>> 
>> #!/usr/local/bin/python
>> 
>> import cgi, string
>> 
>> form = cgi.FieldStorage()
>> 
>> if form.has_key('usernameField') and form.has_key('passwordField'):
>>          users_username = string.strip(form['usernameField'].value)
>>          users_password = string.strip(form['passwordField'].value)
>> 
>> InFile = open('users.dat', 'r')
<nit>
   inFile = file('users.dat')  # file replaces open in newer versions, and 'r' is default
   ^--(unconvential to capitalize unless name of "constant" (all caps) or class (first or mixed caps))
</nit>
>>
UIAM, the rest can be done with just this (untested!):
 
   while 1:
       file_username = string.strip(InFile.readline()) # assumes first line is username
       file_password = string.strip(InFile.readline()) # assumes every username followed by password
       authorized = file_username == users_username and file_password == users_password
       if authorized or not file_username: break       

<nit>
(I assume you're using an old version, or you could use s.strip() instead of string.strip(s))
</nit>

    
>> file_username = string.strip(InFile.readline())
>> file_password = string.strip(InFile.readline())
>> 
>> 
>> 
>> 
>> authorised = 0
>> 
>> while file_username and file_password:
>>        if file_username == users_username:
>>               if file_password == users_password: # correct
>>              authorised = 1
>>       break
>>               else:                               # login matched but not
>> password
>>                     file_username = InFile.readline()
>>              file_password = InFile.readline()
>>        else: # neither match
>>               file_username = InFile.readline()
>>               file_password = InFile.readline()
>> 
>> 
>use the readline method. take advantage of the fact that readline 
>returns an empty string when it reaches EOF, and do:
>while(line):
>	line=readline
>

Regards,
Bengt Richter




More information about the Python-list mailing list