Basic file operation questions

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • alex

    #1

    Basic file operation questions

    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(filen ame, 'r') and what to do then? Can I use
    something like

    for xxx in file:
    ....


    Thanks for help
    Alex

  • Caleb Hattingh

    #2
    Re: Basic file operation questions

    Hi Alex

    Assuming you have a file called "data.txt":

    ***
    f = open('data.txt' ,'r')
    lines = f.readlines()
    f.close()
    for line in lines:
    print line
    ***
    Will print each line of the file.

    You can make a huge investment by setting 2 or 3 hours aside to go through
    the Python tutorial, which gets installed as part of the documentation.
    That tutorial can get you much of the knowledge you will ever need with
    Python.

    thx
    Caleb


    On 2 Feb 2005 13:27:49 -0800, alex <alexander.diet z@mpi-hd.mpg.de> wrote:
    [color=blue]
    > 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(filen ame, 'r') and what to do then? Can I use
    > something like
    >
    > for xxx in file:
    > ....
    >
    >
    > Thanks for help
    > Alex
    >[/color]

    Comment

    • Marcel van den Dungen

      #3
      Re: Basic file operation questions

      alex wrote:[color=blue]
      > 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(filen ame, 'r') and what to do then? Can I use
      > something like
      >
      > for xxx in file:
      > ....
      >
      >
      > Thanks for help
      > Alex
      >[/color]
      take a look at this:
      http://www.devshed.com/c/a/Python/Fi...ent-in-Python/

      HTH,
      -- Marcel

      Comment

      • Steve Holden

        #4
        Re: Basic file operation questions

        alex wrote:
        [color=blue]
        > 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(filen ame, 'r') and what to do then? Can I use
        > something like
        >
        > for xxx in file:
        > ....
        >[/color]
        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).
        [color=blue][color=green][color=darkred]
        >>> f = file("test92.py ", 'r')
        >>> for l in f:[/color][/color][/color]
        ... print l,
        ...
        import os.path

        def getHomeDir():
        ''' Try to find user's home directory, otherwise return current
        directory.''
        '
        try:
        path1=os.path.e xpanduser("~")
        except:
        path1=""
        try:
        path2=os.enviro n["HOME"]
        except:
        path2=""
        try:
        path3=os.enviro n["USERPROFIL E"]
        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()[color=blue][color=green][color=darkred]
        >>>[/color][/color][/color]

        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/

        Comment

        • David Douard

          #5
          Re: Basic file operation questions

          Marcel van den Dungen wrote:
          [color=blue]
          > alex wrote:[color=green]
          >> 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(filen ame, 'r') and what to do then? Can I use
          >> something like
          >>
          >> for xxx in file:
          >> ....
          >>
          >>
          >> Thanks for help
          >> Alex
          >>[/color]
          > take a look at this:
          > http://www.devshed.com/c/a/Python/Fi...ent-in-Python/
          >
          > HTH,
          > -- Marcel[/color]

          Or even have a look at the excellent Gnosis book on the subject (and very
          much more further, but...):
          http://gnosis.cx/TPiP/ which is freely available in text format.

          David




          Comment

          • David Douard

            #6
            Re: Basic file operation questions

            David Douard wrote:
            [color=blue]
            > Marcel van den Dungen wrote:
            >[color=green]
            >> alex wrote:[color=darkred]
            >>> 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(filen ame, 'r') and what to do then? Can I use
            >>> something like
            >>>
            >>> for xxx in file:
            >>> ....
            >>>
            >>>
            >>> Thanks for help
            >>> Alex
            >>>[/color]
            >> take a look at this:
            >> http://www.devshed.com/c/a/Python/Fi...ent-in-Python/
            >>
            >> HTH,
            >> -- Marcel[/color]
            >
            > Or even have a look at the excellent Gnosis book on the subject (and very
            > much more further, but...):
            > http://gnosis.cx/TPiP/ which is freely available in text format.
            >
            > David[/color]

            Just to tell (it's not clear at all in my message): the author of the book
            and creator of Gnosis Software is David Mertz, and the book is published
            by Addison Wesley.
            Sorry

            David

            Comment

            • Caleb Hattingh

              #7
              Re: Basic file operation questions

              Peter, that was very clear, thanks.
              [color=blue]
              > So not only is
              >
              > for line in file(...):
              > # do stuff
              >
              > the most elegant, it is also the fastest. file.readlines( ) comes[/color]
              close, but[color=blue]
              > is only viable for "small" files.[/color]

              Comment

              • Marc Huffnagle

                #8
                Re: Basic file operation questions

                When you read a file with that method, is there an implied close() call
                on the file? I assume there is, but how is that handled?

                Caleb Hattingh wrote:[color=blue]
                > Peter, that was very clear, thanks.
                >
                >[color=green]
                >>So not only is
                >>
                >>for line in file(...):
                >> # do stuff
                >>
                >>the most elegant, it is also the fastest. file.readlines( ) comes[/color]
                >
                > close, but
                >[color=green]
                >>is only viable for "small" files.[/color]
                >
                >[/color]

                Marc

                Comment

                • Jeff Shannon

                  #9
                  Re: Basic file operation questions

                  Marc Huffnagle wrote:
                  [color=blue]
                  > When you read a file with that method, is there an implied close() call
                  > on the file? I assume there is, but how is that handled?
                  >[/color]
                  [...][color=blue][color=green][color=darkred]
                  >>> for line in file(...):
                  >>> # do stuff[/color][/color][/color]

                  As I understand it, the disk file will be closed when the file object
                  is garbage collected. In CPython, that will be as soon as there are
                  no active references to the file; i.e., in the above case, it should
                  happen as soon as the for loop finishes. Jython uses Java's garbage
                  collector, which is a bit less predictable, so the file may not be
                  closed immediately. It *will*, however, be closed during program
                  shutdown if it hasn't happened before then.

                  Jeff Shannon
                  Technician/Programmer
                  Credit International

                  Comment

                  • Caleb Hattingh

                    #10
                    Re: Basic file operation questions

                    Marc

                    I don't know how it is handled, but I expect also that there is an implied
                    close().

                    thanks
                    Caleb
                    [color=blue]
                    > When you read a file with that method, is there an implied close() call
                    > on the file? I assume there is, but how is that handled?[/color]


                    Comment

                    • Grant Edwards

                      #11
                      Re: Basic file operation questions

                      On 2005-02-08, Marc Huffnagle <mhuffnagle@kno wtechnology.net > wrote:
                      [color=blue][color=green][color=darkred]
                      >>>for line in file(...):
                      >>> # do stuff[/color][/color][/color]
                      [color=blue]
                      > When you read a file with that method, is there an implied close() call
                      > on the file? I assume there is, but how is that handled?[/color]

                      The file will be closed when the the file object is deleted by
                      the garbage collection algorithm. That will happen sometime
                      after the for loop exits and before the program exits. In
                      normal C-Python I believe it happens immediately after the for
                      loop exits. However, that behavior is not guaranteed by the
                      language spec.

                      --
                      Grant Edwards grante Yow! Now that I have my
                      at "APPLE", I comprehend COST
                      visi.com ACCOUNTING!!

                      Comment

                      Working...