Why can't I call read() twice on an open file?










79















For an exercise I'm doing, I'm trying to read the contents of a given file twice using the read() method. Strangely, when I call it the second time, it doesn't seem to return the file content as a string?



Here's the code



f = f.open()

# get the year
match = re.search(r'Popularity in (d+)', f.read())

if match:
print match.group(1)

# get all the names
matches = re.findall(r'<td>(d+)</td><td>(w+)</td><td>(w+)</td>', f.read())

if matches:
# matches is always None


Of course I know that this is not the most efficient or best way, this is not the point here. The point is, why can't I call read() twice? Do I have to reset the file handle? Or close / reopen the file in order to do that?










share|improve this question



















  • 2





    Where did you get the idea that read would not change the state of the file? What reference or tutorial are you using?

    – S.Lott
    Oct 11 '10 at 12:29











  • I believe closing and reopening the file should work based on the anwers below.

    – Anthony
    Oct 11 '10 at 12:29











  • @Shynthriir: Closing and reopening the file is not always a good idea since it may have other effects in the system (temporary files, incron, etc.).

    – Ignacio Vazquez-Abrams
    Oct 11 '10 at 12:32






  • 3





    I just want to state the obvious: You DID call read() twice!

    – unbeknown
    Oct 11 '10 at 13:10






  • 4





    W/R/T/ S.Lott, and from 5 years on: this really needs to be in the python documentation. It isn't obvious that one should assume that reading a file object would change state of anything, especially if one is used to working with immutable data/functional-style programming...

    – Paul Gowder
    Oct 2 '15 at 3:34















79















For an exercise I'm doing, I'm trying to read the contents of a given file twice using the read() method. Strangely, when I call it the second time, it doesn't seem to return the file content as a string?



Here's the code



f = f.open()

# get the year
match = re.search(r'Popularity in (d+)', f.read())

if match:
print match.group(1)

# get all the names
matches = re.findall(r'<td>(d+)</td><td>(w+)</td><td>(w+)</td>', f.read())

if matches:
# matches is always None


Of course I know that this is not the most efficient or best way, this is not the point here. The point is, why can't I call read() twice? Do I have to reset the file handle? Or close / reopen the file in order to do that?










share|improve this question



















  • 2





    Where did you get the idea that read would not change the state of the file? What reference or tutorial are you using?

    – S.Lott
    Oct 11 '10 at 12:29











  • I believe closing and reopening the file should work based on the anwers below.

    – Anthony
    Oct 11 '10 at 12:29











  • @Shynthriir: Closing and reopening the file is not always a good idea since it may have other effects in the system (temporary files, incron, etc.).

    – Ignacio Vazquez-Abrams
    Oct 11 '10 at 12:32






  • 3





    I just want to state the obvious: You DID call read() twice!

    – unbeknown
    Oct 11 '10 at 13:10






  • 4





    W/R/T/ S.Lott, and from 5 years on: this really needs to be in the python documentation. It isn't obvious that one should assume that reading a file object would change state of anything, especially if one is used to working with immutable data/functional-style programming...

    – Paul Gowder
    Oct 2 '15 at 3:34













79












79








79


19






For an exercise I'm doing, I'm trying to read the contents of a given file twice using the read() method. Strangely, when I call it the second time, it doesn't seem to return the file content as a string?



Here's the code



f = f.open()

# get the year
match = re.search(r'Popularity in (d+)', f.read())

if match:
print match.group(1)

# get all the names
matches = re.findall(r'<td>(d+)</td><td>(w+)</td><td>(w+)</td>', f.read())

if matches:
# matches is always None


Of course I know that this is not the most efficient or best way, this is not the point here. The point is, why can't I call read() twice? Do I have to reset the file handle? Or close / reopen the file in order to do that?










share|improve this question
















For an exercise I'm doing, I'm trying to read the contents of a given file twice using the read() method. Strangely, when I call it the second time, it doesn't seem to return the file content as a string?



Here's the code



f = f.open()

# get the year
match = re.search(r'Popularity in (d+)', f.read())

if match:
print match.group(1)

# get all the names
matches = re.findall(r'<td>(d+)</td><td>(w+)</td><td>(w+)</td>', f.read())

if matches:
# matches is always None


Of course I know that this is not the most efficient or best way, this is not the point here. The point is, why can't I call read() twice? Do I have to reset the file handle? Or close / reopen the file in order to do that?







python io






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Jan 14 '16 at 15:46









Glen Selle

3,23743056




3,23743056










asked Oct 11 '10 at 12:25









helpermethodhelpermethod

23.7k50150241




23.7k50150241







  • 2





    Where did you get the idea that read would not change the state of the file? What reference or tutorial are you using?

    – S.Lott
    Oct 11 '10 at 12:29











  • I believe closing and reopening the file should work based on the anwers below.

    – Anthony
    Oct 11 '10 at 12:29











  • @Shynthriir: Closing and reopening the file is not always a good idea since it may have other effects in the system (temporary files, incron, etc.).

    – Ignacio Vazquez-Abrams
    Oct 11 '10 at 12:32






  • 3





    I just want to state the obvious: You DID call read() twice!

    – unbeknown
    Oct 11 '10 at 13:10






  • 4





    W/R/T/ S.Lott, and from 5 years on: this really needs to be in the python documentation. It isn't obvious that one should assume that reading a file object would change state of anything, especially if one is used to working with immutable data/functional-style programming...

    – Paul Gowder
    Oct 2 '15 at 3:34












  • 2





    Where did you get the idea that read would not change the state of the file? What reference or tutorial are you using?

    – S.Lott
    Oct 11 '10 at 12:29











  • I believe closing and reopening the file should work based on the anwers below.

    – Anthony
    Oct 11 '10 at 12:29











  • @Shynthriir: Closing and reopening the file is not always a good idea since it may have other effects in the system (temporary files, incron, etc.).

    – Ignacio Vazquez-Abrams
    Oct 11 '10 at 12:32






  • 3





    I just want to state the obvious: You DID call read() twice!

    – unbeknown
    Oct 11 '10 at 13:10






  • 4





    W/R/T/ S.Lott, and from 5 years on: this really needs to be in the python documentation. It isn't obvious that one should assume that reading a file object would change state of anything, especially if one is used to working with immutable data/functional-style programming...

    – Paul Gowder
    Oct 2 '15 at 3:34







2




2





Where did you get the idea that read would not change the state of the file? What reference or tutorial are you using?

– S.Lott
Oct 11 '10 at 12:29





Where did you get the idea that read would not change the state of the file? What reference or tutorial are you using?

– S.Lott
Oct 11 '10 at 12:29













I believe closing and reopening the file should work based on the anwers below.

– Anthony
Oct 11 '10 at 12:29





I believe closing and reopening the file should work based on the anwers below.

– Anthony
Oct 11 '10 at 12:29













@Shynthriir: Closing and reopening the file is not always a good idea since it may have other effects in the system (temporary files, incron, etc.).

– Ignacio Vazquez-Abrams
Oct 11 '10 at 12:32





@Shynthriir: Closing and reopening the file is not always a good idea since it may have other effects in the system (temporary files, incron, etc.).

– Ignacio Vazquez-Abrams
Oct 11 '10 at 12:32




3




3





I just want to state the obvious: You DID call read() twice!

– unbeknown
Oct 11 '10 at 13:10





I just want to state the obvious: You DID call read() twice!

– unbeknown
Oct 11 '10 at 13:10




4




4





W/R/T/ S.Lott, and from 5 years on: this really needs to be in the python documentation. It isn't obvious that one should assume that reading a file object would change state of anything, especially if one is used to working with immutable data/functional-style programming...

– Paul Gowder
Oct 2 '15 at 3:34





W/R/T/ S.Lott, and from 5 years on: this really needs to be in the python documentation. It isn't obvious that one should assume that reading a file object would change state of anything, especially if one is used to working with immutable data/functional-style programming...

– Paul Gowder
Oct 2 '15 at 3:34












7 Answers
7






active

oldest

votes


















122














Calling read() reads through the entire file and leaves the read cursor at the end of the file (with nothing more to read). If you are looking to read a certain number of lines at a time you could use readline(), readlines() or iterate through lines with for line in handle:.



To answer your question directly, once a file has been read, with read() you can use seek(0) to return the read cursor to the start of the file (docs are here). If you know the file isn't going to be too large, you can also save the read() output to a variable, using it in your findall expressions.



Ps. Dont forget to close the file after you are done with it ;)






share|improve this answer




















  • 3





    +1, Yes, please read to temporary variable to avoid unnecessary file I/O. It's a false economy that you're saving any memory because you have fewer (explicit) variables.

    – Nick T
    Oct 11 '10 at 13:45






  • 2





    @NickT: I would expect that a small file being read multiple times gets cached by the OS (at least on Linux/OSX), so no extra file I/O for reading in twice. Large files that don't fit in memory don't get cached, but you don't want to read them into a variable because you'll start swapping. So in case of doubt, always read multiple times. If you know for sure the files are small, do whatever gives the nicest program.

    – Claude
    Jun 4 '14 at 13:41






  • 2





    Tear down can be automated with with.

    – Cees Timmerman
    Jan 19 '16 at 16:47


















19














yeah, as above...



i'll write just an example:



>>> a = open('file.txt')
>>> a.read()
#output
>>> a.seek(0)
>>> a.read()
#same output





share|improve this answer






























    15














    Everyone who has answered this question so far is absolutely right - read() moves through the file, so after you've called it, you can't call it again.



    What I'll add is that in your particular case, you don't need to seek back to the start or reopen the file, you can just store the text that you've read in a local variable, and use it twice, or as many times as you like, in your program:



    f = f.open()
    text = f.read() # read the file into a local variable
    # get the year
    match = re.search(r'Popularity in (d+)', text)
    if match:
    print match.group(1)
    # get all the names
    matches = re.findall(r'<td>(d+)</td><td>(w+)</td><td>(w+)</td>', text)
    if matches:
    # matches will now not always be None





    share|improve this answer




















    • 1





      +1 Actually this was the proposed solution for this exercise (code.google.com/intl/de-DE/edu/languages/google-python-class/…). But somehow I didn't thought of storing the string in a variable. D'oh!

      – helpermethod
      Oct 11 '10 at 17:33






    • 1





      With Python3, use pathlib. from pathlib import Path; text = Path(filename).read_text() Takes care of open, close, etc.

      – PaulMcG
      Jun 19 '17 at 12:06


















    13














    The read pointer moves to after the last read byte/character. Use the seek() method to rewind the read pointer to the beginning.






    share|improve this answer






























      2














      Every open file has an associated position.

      When you read() you read from that position.
      For example read(10) reads the first 10 bytes from a newly opened file, then another read(10) reads the next 10 bytes.
      read() without arguments reads all of the contents of the file, leaving the file position at the end of the file. Next time you call read() there is nothing to read.



      You can use seek to move the file position. Or probably better in your case would be to do one read() and keep the result for both searches.






      share|improve this answer






























        1














        read() consumes. So, you could reset the file, or seek to the start before re-reading. Or, if it suites your task, you can use read(n) to consume only n bytes.






        share|improve this answer






























          1














          I always find the read method something of a walk down a dark alley. You go down a bit and stop but if you are not counting your steps you are not sure how far along you are. Seek gives the solution by repositioning, the other option is Tell which returns the position along the file. May be the Python file api can combine read and seek into a read_from(position,bytes) to make it simpler - till that happens you should read this page.






          share|improve this answer






















            Your Answer






            StackExchange.ifUsing("editor", function ()
            StackExchange.using("externalEditor", function ()
            StackExchange.using("snippets", function ()
            StackExchange.snippets.init();
            );
            );
            , "code-snippets");

            StackExchange.ready(function()
            var channelOptions =
            tags: "".split(" "),
            id: "1"
            ;
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function()
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled)
            StackExchange.using("snippets", function()
            createEditor();
            );

            else
            createEditor();

            );

            function createEditor()
            StackExchange.prepareEditor(
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader:
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            ,
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            );



            );













            draft saved

            draft discarded


















            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f3906137%2fwhy-cant-i-call-read-twice-on-an-open-file%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown

























            7 Answers
            7






            active

            oldest

            votes








            7 Answers
            7






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            122














            Calling read() reads through the entire file and leaves the read cursor at the end of the file (with nothing more to read). If you are looking to read a certain number of lines at a time you could use readline(), readlines() or iterate through lines with for line in handle:.



            To answer your question directly, once a file has been read, with read() you can use seek(0) to return the read cursor to the start of the file (docs are here). If you know the file isn't going to be too large, you can also save the read() output to a variable, using it in your findall expressions.



            Ps. Dont forget to close the file after you are done with it ;)






            share|improve this answer




















            • 3





              +1, Yes, please read to temporary variable to avoid unnecessary file I/O. It's a false economy that you're saving any memory because you have fewer (explicit) variables.

              – Nick T
              Oct 11 '10 at 13:45






            • 2





              @NickT: I would expect that a small file being read multiple times gets cached by the OS (at least on Linux/OSX), so no extra file I/O for reading in twice. Large files that don't fit in memory don't get cached, but you don't want to read them into a variable because you'll start swapping. So in case of doubt, always read multiple times. If you know for sure the files are small, do whatever gives the nicest program.

              – Claude
              Jun 4 '14 at 13:41






            • 2





              Tear down can be automated with with.

              – Cees Timmerman
              Jan 19 '16 at 16:47















            122














            Calling read() reads through the entire file and leaves the read cursor at the end of the file (with nothing more to read). If you are looking to read a certain number of lines at a time you could use readline(), readlines() or iterate through lines with for line in handle:.



            To answer your question directly, once a file has been read, with read() you can use seek(0) to return the read cursor to the start of the file (docs are here). If you know the file isn't going to be too large, you can also save the read() output to a variable, using it in your findall expressions.



            Ps. Dont forget to close the file after you are done with it ;)






            share|improve this answer




















            • 3





              +1, Yes, please read to temporary variable to avoid unnecessary file I/O. It's a false economy that you're saving any memory because you have fewer (explicit) variables.

              – Nick T
              Oct 11 '10 at 13:45






            • 2





              @NickT: I would expect that a small file being read multiple times gets cached by the OS (at least on Linux/OSX), so no extra file I/O for reading in twice. Large files that don't fit in memory don't get cached, but you don't want to read them into a variable because you'll start swapping. So in case of doubt, always read multiple times. If you know for sure the files are small, do whatever gives the nicest program.

              – Claude
              Jun 4 '14 at 13:41






            • 2





              Tear down can be automated with with.

              – Cees Timmerman
              Jan 19 '16 at 16:47













            122












            122








            122







            Calling read() reads through the entire file and leaves the read cursor at the end of the file (with nothing more to read). If you are looking to read a certain number of lines at a time you could use readline(), readlines() or iterate through lines with for line in handle:.



            To answer your question directly, once a file has been read, with read() you can use seek(0) to return the read cursor to the start of the file (docs are here). If you know the file isn't going to be too large, you can also save the read() output to a variable, using it in your findall expressions.



            Ps. Dont forget to close the file after you are done with it ;)






            share|improve this answer















            Calling read() reads through the entire file and leaves the read cursor at the end of the file (with nothing more to read). If you are looking to read a certain number of lines at a time you could use readline(), readlines() or iterate through lines with for line in handle:.



            To answer your question directly, once a file has been read, with read() you can use seek(0) to return the read cursor to the start of the file (docs are here). If you know the file isn't going to be too large, you can also save the read() output to a variable, using it in your findall expressions.



            Ps. Dont forget to close the file after you are done with it ;)







            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Aug 27 '13 at 0:20









            Nunser

            4,40381934




            4,40381934










            answered Oct 11 '10 at 12:27









            TimTim

            4,33122233




            4,33122233







            • 3





              +1, Yes, please read to temporary variable to avoid unnecessary file I/O. It's a false economy that you're saving any memory because you have fewer (explicit) variables.

              – Nick T
              Oct 11 '10 at 13:45






            • 2





              @NickT: I would expect that a small file being read multiple times gets cached by the OS (at least on Linux/OSX), so no extra file I/O for reading in twice. Large files that don't fit in memory don't get cached, but you don't want to read them into a variable because you'll start swapping. So in case of doubt, always read multiple times. If you know for sure the files are small, do whatever gives the nicest program.

              – Claude
              Jun 4 '14 at 13:41






            • 2





              Tear down can be automated with with.

              – Cees Timmerman
              Jan 19 '16 at 16:47












            • 3





              +1, Yes, please read to temporary variable to avoid unnecessary file I/O. It's a false economy that you're saving any memory because you have fewer (explicit) variables.

              – Nick T
              Oct 11 '10 at 13:45






            • 2





              @NickT: I would expect that a small file being read multiple times gets cached by the OS (at least on Linux/OSX), so no extra file I/O for reading in twice. Large files that don't fit in memory don't get cached, but you don't want to read them into a variable because you'll start swapping. So in case of doubt, always read multiple times. If you know for sure the files are small, do whatever gives the nicest program.

              – Claude
              Jun 4 '14 at 13:41






            • 2





              Tear down can be automated with with.

              – Cees Timmerman
              Jan 19 '16 at 16:47







            3




            3





            +1, Yes, please read to temporary variable to avoid unnecessary file I/O. It's a false economy that you're saving any memory because you have fewer (explicit) variables.

            – Nick T
            Oct 11 '10 at 13:45





            +1, Yes, please read to temporary variable to avoid unnecessary file I/O. It's a false economy that you're saving any memory because you have fewer (explicit) variables.

            – Nick T
            Oct 11 '10 at 13:45




            2




            2





            @NickT: I would expect that a small file being read multiple times gets cached by the OS (at least on Linux/OSX), so no extra file I/O for reading in twice. Large files that don't fit in memory don't get cached, but you don't want to read them into a variable because you'll start swapping. So in case of doubt, always read multiple times. If you know for sure the files are small, do whatever gives the nicest program.

            – Claude
            Jun 4 '14 at 13:41





            @NickT: I would expect that a small file being read multiple times gets cached by the OS (at least on Linux/OSX), so no extra file I/O for reading in twice. Large files that don't fit in memory don't get cached, but you don't want to read them into a variable because you'll start swapping. So in case of doubt, always read multiple times. If you know for sure the files are small, do whatever gives the nicest program.

            – Claude
            Jun 4 '14 at 13:41




            2




            2





            Tear down can be automated with with.

            – Cees Timmerman
            Jan 19 '16 at 16:47





            Tear down can be automated with with.

            – Cees Timmerman
            Jan 19 '16 at 16:47













            19














            yeah, as above...



            i'll write just an example:



            >>> a = open('file.txt')
            >>> a.read()
            #output
            >>> a.seek(0)
            >>> a.read()
            #same output





            share|improve this answer



























              19














              yeah, as above...



              i'll write just an example:



              >>> a = open('file.txt')
              >>> a.read()
              #output
              >>> a.seek(0)
              >>> a.read()
              #same output





              share|improve this answer

























                19












                19








                19







                yeah, as above...



                i'll write just an example:



                >>> a = open('file.txt')
                >>> a.read()
                #output
                >>> a.seek(0)
                >>> a.read()
                #same output





                share|improve this answer













                yeah, as above...



                i'll write just an example:



                >>> a = open('file.txt')
                >>> a.read()
                #output
                >>> a.seek(0)
                >>> a.read()
                #same output






                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Oct 11 '10 at 13:20









                AntAnt

                3,49711738




                3,49711738





















                    15














                    Everyone who has answered this question so far is absolutely right - read() moves through the file, so after you've called it, you can't call it again.



                    What I'll add is that in your particular case, you don't need to seek back to the start or reopen the file, you can just store the text that you've read in a local variable, and use it twice, or as many times as you like, in your program:



                    f = f.open()
                    text = f.read() # read the file into a local variable
                    # get the year
                    match = re.search(r'Popularity in (d+)', text)
                    if match:
                    print match.group(1)
                    # get all the names
                    matches = re.findall(r'<td>(d+)</td><td>(w+)</td><td>(w+)</td>', text)
                    if matches:
                    # matches will now not always be None





                    share|improve this answer




















                    • 1





                      +1 Actually this was the proposed solution for this exercise (code.google.com/intl/de-DE/edu/languages/google-python-class/…). But somehow I didn't thought of storing the string in a variable. D'oh!

                      – helpermethod
                      Oct 11 '10 at 17:33






                    • 1





                      With Python3, use pathlib. from pathlib import Path; text = Path(filename).read_text() Takes care of open, close, etc.

                      – PaulMcG
                      Jun 19 '17 at 12:06















                    15














                    Everyone who has answered this question so far is absolutely right - read() moves through the file, so after you've called it, you can't call it again.



                    What I'll add is that in your particular case, you don't need to seek back to the start or reopen the file, you can just store the text that you've read in a local variable, and use it twice, or as many times as you like, in your program:



                    f = f.open()
                    text = f.read() # read the file into a local variable
                    # get the year
                    match = re.search(r'Popularity in (d+)', text)
                    if match:
                    print match.group(1)
                    # get all the names
                    matches = re.findall(r'<td>(d+)</td><td>(w+)</td><td>(w+)</td>', text)
                    if matches:
                    # matches will now not always be None





                    share|improve this answer




















                    • 1





                      +1 Actually this was the proposed solution for this exercise (code.google.com/intl/de-DE/edu/languages/google-python-class/…). But somehow I didn't thought of storing the string in a variable. D'oh!

                      – helpermethod
                      Oct 11 '10 at 17:33






                    • 1





                      With Python3, use pathlib. from pathlib import Path; text = Path(filename).read_text() Takes care of open, close, etc.

                      – PaulMcG
                      Jun 19 '17 at 12:06













                    15












                    15








                    15







                    Everyone who has answered this question so far is absolutely right - read() moves through the file, so after you've called it, you can't call it again.



                    What I'll add is that in your particular case, you don't need to seek back to the start or reopen the file, you can just store the text that you've read in a local variable, and use it twice, or as many times as you like, in your program:



                    f = f.open()
                    text = f.read() # read the file into a local variable
                    # get the year
                    match = re.search(r'Popularity in (d+)', text)
                    if match:
                    print match.group(1)
                    # get all the names
                    matches = re.findall(r'<td>(d+)</td><td>(w+)</td><td>(w+)</td>', text)
                    if matches:
                    # matches will now not always be None





                    share|improve this answer















                    Everyone who has answered this question so far is absolutely right - read() moves through the file, so after you've called it, you can't call it again.



                    What I'll add is that in your particular case, you don't need to seek back to the start or reopen the file, you can just store the text that you've read in a local variable, and use it twice, or as many times as you like, in your program:



                    f = f.open()
                    text = f.read() # read the file into a local variable
                    # get the year
                    match = re.search(r'Popularity in (d+)', text)
                    if match:
                    print match.group(1)
                    # get all the names
                    matches = re.findall(r'<td>(d+)</td><td>(w+)</td><td>(w+)</td>', text)
                    if matches:
                    # matches will now not always be None






                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    edited Jan 14 '16 at 15:47









                    Glen Selle

                    3,23743056




                    3,23743056










                    answered Oct 11 '10 at 12:34









                    Tom AndersonTom Anderson

                    37.5k1174110




                    37.5k1174110







                    • 1





                      +1 Actually this was the proposed solution for this exercise (code.google.com/intl/de-DE/edu/languages/google-python-class/…). But somehow I didn't thought of storing the string in a variable. D'oh!

                      – helpermethod
                      Oct 11 '10 at 17:33






                    • 1





                      With Python3, use pathlib. from pathlib import Path; text = Path(filename).read_text() Takes care of open, close, etc.

                      – PaulMcG
                      Jun 19 '17 at 12:06












                    • 1





                      +1 Actually this was the proposed solution for this exercise (code.google.com/intl/de-DE/edu/languages/google-python-class/…). But somehow I didn't thought of storing the string in a variable. D'oh!

                      – helpermethod
                      Oct 11 '10 at 17:33






                    • 1





                      With Python3, use pathlib. from pathlib import Path; text = Path(filename).read_text() Takes care of open, close, etc.

                      – PaulMcG
                      Jun 19 '17 at 12:06







                    1




                    1





                    +1 Actually this was the proposed solution for this exercise (code.google.com/intl/de-DE/edu/languages/google-python-class/…). But somehow I didn't thought of storing the string in a variable. D'oh!

                    – helpermethod
                    Oct 11 '10 at 17:33





                    +1 Actually this was the proposed solution for this exercise (code.google.com/intl/de-DE/edu/languages/google-python-class/…). But somehow I didn't thought of storing the string in a variable. D'oh!

                    – helpermethod
                    Oct 11 '10 at 17:33




                    1




                    1





                    With Python3, use pathlib. from pathlib import Path; text = Path(filename).read_text() Takes care of open, close, etc.

                    – PaulMcG
                    Jun 19 '17 at 12:06





                    With Python3, use pathlib. from pathlib import Path; text = Path(filename).read_text() Takes care of open, close, etc.

                    – PaulMcG
                    Jun 19 '17 at 12:06











                    13














                    The read pointer moves to after the last read byte/character. Use the seek() method to rewind the read pointer to the beginning.






                    share|improve this answer



























                      13














                      The read pointer moves to after the last read byte/character. Use the seek() method to rewind the read pointer to the beginning.






                      share|improve this answer

























                        13












                        13








                        13







                        The read pointer moves to after the last read byte/character. Use the seek() method to rewind the read pointer to the beginning.






                        share|improve this answer













                        The read pointer moves to after the last read byte/character. Use the seek() method to rewind the read pointer to the beginning.







                        share|improve this answer












                        share|improve this answer



                        share|improve this answer










                        answered Oct 11 '10 at 12:27









                        Ignacio Vazquez-AbramsIgnacio Vazquez-Abrams

                        587k10710701172




                        587k10710701172





















                            2














                            Every open file has an associated position.

                            When you read() you read from that position.
                            For example read(10) reads the first 10 bytes from a newly opened file, then another read(10) reads the next 10 bytes.
                            read() without arguments reads all of the contents of the file, leaving the file position at the end of the file. Next time you call read() there is nothing to read.



                            You can use seek to move the file position. Or probably better in your case would be to do one read() and keep the result for both searches.






                            share|improve this answer



























                              2














                              Every open file has an associated position.

                              When you read() you read from that position.
                              For example read(10) reads the first 10 bytes from a newly opened file, then another read(10) reads the next 10 bytes.
                              read() without arguments reads all of the contents of the file, leaving the file position at the end of the file. Next time you call read() there is nothing to read.



                              You can use seek to move the file position. Or probably better in your case would be to do one read() and keep the result for both searches.






                              share|improve this answer

























                                2












                                2








                                2







                                Every open file has an associated position.

                                When you read() you read from that position.
                                For example read(10) reads the first 10 bytes from a newly opened file, then another read(10) reads the next 10 bytes.
                                read() without arguments reads all of the contents of the file, leaving the file position at the end of the file. Next time you call read() there is nothing to read.



                                You can use seek to move the file position. Or probably better in your case would be to do one read() and keep the result for both searches.






                                share|improve this answer













                                Every open file has an associated position.

                                When you read() you read from that position.
                                For example read(10) reads the first 10 bytes from a newly opened file, then another read(10) reads the next 10 bytes.
                                read() without arguments reads all of the contents of the file, leaving the file position at the end of the file. Next time you call read() there is nothing to read.



                                You can use seek to move the file position. Or probably better in your case would be to do one read() and keep the result for both searches.







                                share|improve this answer












                                share|improve this answer



                                share|improve this answer










                                answered Oct 11 '10 at 12:31









                                Douglas LeederDouglas Leeder

                                44k878120




                                44k878120





















                                    1














                                    read() consumes. So, you could reset the file, or seek to the start before re-reading. Or, if it suites your task, you can use read(n) to consume only n bytes.






                                    share|improve this answer



























                                      1














                                      read() consumes. So, you could reset the file, or seek to the start before re-reading. Or, if it suites your task, you can use read(n) to consume only n bytes.






                                      share|improve this answer

























                                        1












                                        1








                                        1







                                        read() consumes. So, you could reset the file, or seek to the start before re-reading. Or, if it suites your task, you can use read(n) to consume only n bytes.






                                        share|improve this answer













                                        read() consumes. So, you could reset the file, or seek to the start before re-reading. Or, if it suites your task, you can use read(n) to consume only n bytes.







                                        share|improve this answer












                                        share|improve this answer



                                        share|improve this answer










                                        answered Oct 11 '10 at 13:15









                                        towitowi

                                        10.1k1878150




                                        10.1k1878150





















                                            1














                                            I always find the read method something of a walk down a dark alley. You go down a bit and stop but if you are not counting your steps you are not sure how far along you are. Seek gives the solution by repositioning, the other option is Tell which returns the position along the file. May be the Python file api can combine read and seek into a read_from(position,bytes) to make it simpler - till that happens you should read this page.






                                            share|improve this answer



























                                              1














                                              I always find the read method something of a walk down a dark alley. You go down a bit and stop but if you are not counting your steps you are not sure how far along you are. Seek gives the solution by repositioning, the other option is Tell which returns the position along the file. May be the Python file api can combine read and seek into a read_from(position,bytes) to make it simpler - till that happens you should read this page.






                                              share|improve this answer

























                                                1












                                                1








                                                1







                                                I always find the read method something of a walk down a dark alley. You go down a bit and stop but if you are not counting your steps you are not sure how far along you are. Seek gives the solution by repositioning, the other option is Tell which returns the position along the file. May be the Python file api can combine read and seek into a read_from(position,bytes) to make it simpler - till that happens you should read this page.






                                                share|improve this answer













                                                I always find the read method something of a walk down a dark alley. You go down a bit and stop but if you are not counting your steps you are not sure how far along you are. Seek gives the solution by repositioning, the other option is Tell which returns the position along the file. May be the Python file api can combine read and seek into a read_from(position,bytes) to make it simpler - till that happens you should read this page.







                                                share|improve this answer












                                                share|improve this answer



                                                share|improve this answer










                                                answered Oct 11 '10 at 13:34









                                                whatnickwhatnick

                                                4,5361534




                                                4,5361534



























                                                    draft saved

                                                    draft discarded
















































                                                    Thanks for contributing an answer to Stack Overflow!


                                                    • Please be sure to answer the question. Provide details and share your research!

                                                    But avoid


                                                    • Asking for help, clarification, or responding to other answers.

                                                    • Making statements based on opinion; back them up with references or personal experience.

                                                    To learn more, see our tips on writing great answers.




                                                    draft saved


                                                    draft discarded














                                                    StackExchange.ready(
                                                    function ()
                                                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f3906137%2fwhy-cant-i-call-read-twice-on-an-open-file%23new-answer', 'question_page');

                                                    );

                                                    Post as a guest















                                                    Required, but never shown





















































                                                    Required, but never shown














                                                    Required, but never shown












                                                    Required, but never shown







                                                    Required, but never shown

































                                                    Required, but never shown














                                                    Required, but never shown












                                                    Required, but never shown







                                                    Required, but never shown







                                                    Popular posts from this blog

                                                    Top Tejano songwriter Luis Silva dead of heart attack at 64

                                                    政党

                                                    天津地下鉄3号線