Is this what you are looking for?<br><br>#!/usr/bin/python<br>'makeTextFile.py -- create text file'<br><br>import os<br><br># get filename<br>#while True:<br># fname = raw_input('Enter file name: ')<br># if
os.path.exists(fname):<br># print"*** ERROR: '%s' already exists" % fname<br># else:<br># break<br><br>while True:<br> fname = raw_input('Enter file name: ')<br> try:<br>
fobj = open(fname, 'r')<br> except:<br> break<br><br># get file content (text) lines<br>all = []<br>print "\nEnter lines ('.' by itself to quit).\n"<br><br># loop until user terminates input
<br>while True:<br> entry = raw_input('> ')<br> if entry == '.':<br> break<br> else:<br> all.append(entry)<br><br># write lines to file with NEWLINE line terminator<br>fobj = open(fname, 'w')
<br>fobj.write('\n'.join(all))<br>fobj.close()<br>print 'DONE!'<br clear="all"><br>-- <br>Arvind Deshpande
<br><br><div><span class="gmail_quote">On 9/8/07, <b class="gmail_sendername">Alan Gauld</b> <<a href="mailto:alan.gauld@btinternet.com">alan.gauld@btinternet.com</a>> wrote:</span><blockquote class="gmail_quote" style="border-left: 1px solid rgb(204, 204, 204); margin: 0pt 0pt 0pt 0.8ex; padding-left: 1ex;">
"Christopher Spears" <<a href="mailto:cspears2002@yahoo.com">cspears2002@yahoo.com</a>> wrote<br><br>> I have been asked to replace this while loop with a<br>> try and except clause:<br>><br>> while True:
<br>> fname = raw_input('Enter file name: ')<br>> if os.path.exists(fname):<br>> print"*** ERROR: '%s' already exists" % fname<br>> else:<br>> break<br>><br>
> I'm not sure how to do this. I looked at the back of<br>> the book, and I don't see an exception that is raised<br>> when a previously existing file is found. Any hints?<br><br>The loop simply detects if the file exists *or not*
<br>If the file does not exist you exit the loop.<br>Can you find a way using try/except to detect<br>if the file does not exist?<br><br>That will replace the body of the while loop,<br>I can't think of any way to replace the loop itself
<br>with try./except...<br><br>And I agree this is not an obvious place to use<br>try/except. Your earlier example is more typical.<br><br>--<br>Alan Gauld<br>Author of the Learn to Program web site<br><a href="http://www.freenetpages.co.uk/hp/alan.gauld">
http://www.freenetpages.co.uk/hp/alan.gauld</a><br><br>_______________________________________________<br>Tutor maillist - <a href="mailto:Tutor@python.org">Tutor@python.org</a><br><a href="http://mail.python.org/mailman/listinfo/tutor">
http://mail.python.org/mailman/listinfo/tutor</a><br></blockquote></div><br>