[Tutor] How to write strings with new line character in a file

Kent Johnson kent37 at tds.net
Fri Oct 13 13:37:05 CEST 2006


Asrarahmed Kadri wrote:
> Here is the complete code:
> fd is the file handle.
>  
> import sys
> 
>  def check_dup(fd1):
>     print fd1
>     fd1.seek(0,0)
>     done = 0
>     list1 = []
>     while not done:
>         x = fd1.readline()
>         if x == "":
>             done = 1
>         else:
>             list1.append(x)
>     return list1
> 
>    
> fname = raw_input("Enter the file name to write data to:\t")
> 
> fd = open(fname,'a+')
> print fd
> done = 0
> 
> while not done:
>     str = raw_input("Enter login name:\t to quit type 'q'")
>    
>     if str == 'q':
>         done = 1
>     else:
>         flag = check_dup(fd)
>         print flag
>         if str in flag:
>             print "Login already exists.!!"
>         else:
>             fd.seek(0,2)
>             fd.write(str + '\n')

I don't know why this isn't working, but I do know a better way to write 
it that will work. Keep the list of login names in a list in memory 
until you have all the names, then write them to a file. Your program 
will look something like this:

ask the file name
open the file for reading and read all the names into a list
close the file

while not done:
   ask the user for a name
   if the name is not in the list:
     add the name to the list

open the file for writing
write the list to the file
close the file

Kent



More information about the Tutor mailing list