Python truncate lines as they are read

后端 未结 7 577
梦毁少年i
梦毁少年i 2020-12-17 17:10

I have an application that reads lines from a file and runs its magic on each line as it is read. Once the line is read and properly processed, I would like to delete the li

相关标签:
7条回答
  • 2020-12-17 17:45

    This is what I use for file based queues. It returns the first line and rewrites the file with the rest. When it's done it returns None:

    def pop_a_text_line(filename):
        with open(filename,'r') as f:
            S = f.readlines()
        if len(S) > 0:
            pop = S[0]
            with open(filename,'w') as f:
                f.writelines(S[1:])
        else:
            pop = None
        return pop
    
    0 讨论(0)
提交回复
热议问题