Reusing a python filehandler?

前端 未结 2 1963
故里飘歌
故里飘歌 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: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.

提交回复
热议问题