Reusing a python filehandler?

前端 未结 2 1936
故里飘歌
故里飘歌 2021-01-25 02:39

I am a new to python and I need a help to understand the codes below -

def main():
    print(\'main\')

    fh = open(\'C:\\\\Python\\\\lines.txt\')
    for lin         


        
相关标签:
2条回答
  • 2021-01-25 03:13

    Your file handle contains a position pointer. You can find out where you're at using fh.tell. It will move through the file for each line. Once you reach the end of the line, if you want to iterate through it again, you need to reset this pointer. fh.seek(0) would accomplish that for you.

    0 讨论(0)
  • 2021-01-25 03:20

    You should read through a primer or a tutorial on the best practices with dealing with file handlers. As you did not close the first instance of fh, in larger programs you will run into issues where the system kernel will fail your program for having too many open file handles, which is definitely a bad thing. In traditional languages you have to do a lot more dancing, but in python you can just use the context manager:

    with open('C:\\Python\\lines.txt') as fh:
        for line in fh.readlines():
            print(line, end = '')
    

    Naturally, the file position is something that is changed whenever the file is read, and that will put the position towards the end, so if you want to do this

    with open('C:\\Python\\lines.txt') as fh:
        for line in fh.readlines():
            print(line, end = '')
    
        for line in fh.readlines():
            print(index, line, end = '')
    

    The second set of read will not be able to read anything unless you do fh.seek(0) in between the two for loops.

    0 讨论(0)
提交回复
热议问题