[Tutor] How to write strings with new line character in a file OOPS CORRECTION
Bob Gailer
bgailer at alum.rpi.edu
Sat Oct 14 01:55:54 CEST 2006
Bob Gailer wrote:
> 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')
>>
>>
> Thank you. I can't get this to fail, so I wonder whether it has to do
> with permissions? What OS are you running on?
>
> Also note when you open a file for output (append or write) it is
> inadvisable to change the file position or to read it ( as you are doing).
>
> As Kent points out there are better ways to do what you are doing. My
> (minimalist?) version is:
>
> fname = raw_input("Enter the file name to write data to:\t")
> fd = open(fname,'a+')
> names = set()
> while 1:
> name = raw_input("Enter login name:\t to quit type 'q'")
> if name == 'q': break
> if name in names: print "Login already exists.!!"
> names.add(name)
> fname.write('\n'.join(names)) <<<< OOPS
>
Should be fd.write('\n'.join(names))
>
>
--
Bob Gailer
510-978-4454
More information about the Tutor
mailing list