alex wrote:

Hi,

I am a beginner with python and here is my first question:
How can I read the contents of a file using a loop or something? I open
the file with file=open(filename, 'r') and what to do then? Can I use
something like

for xxx in file:
   ....

Yes, indeed you can. That's by no means *all* you can do, but to iterate over the lines of the file that will wrok exactly. Note that the lines will still have their terminating "\n" on the end, which is why the print statement inthe following example ends in a comma (this stops print from putting out its own newline).

 >>> f = file("test92.py", 'r')
 >>> for l in f:
 ...   print l,
 ...
import os.path

def getHomeDir():
''' Try to find user's home directory, otherwise return current directory.''
'
try:
path1=os.path.expanduser("~")
except:
path1=""
try:
path2=os.environ["HOME"]
except:
path2=""
try:
path3=os.environ["USERPROFILE"]
except:
path3=""


    if not os.path.exists(path1):
        if not os.path.exists(path2):
            if not os.path.exists(path3):
                return os.getcwd()
            else: return path3
        else: return path2
    else: return path1

print getHomeDir()
 >>>

regards
 Steve
--
Meet the Python developers and your c.l.py favorites March 23-25
Come to PyCon DC 2005          http://www.python.org/pycon/2005/
Steve Holden                           http://www.holdenweb.com/
--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to