Concatenate multiple files into a single file object without creating a new file

前端 未结 8 2271
迷失自我
迷失自我 2021-02-12 16:37

This question is related to Python concatenate text files

I have a list of file_names, like [\'file1.txt\', \'file2.txt\', ...].

I wou

8条回答
  •  情深已故
    2021-02-12 17:17

    try something along this lines:

    def read_files(*filenames):
        for filename in filenames:
            with open(filename,'r') as file_obj:
                for line in file_obj:
                    yield line
    

    you can call it with

    for line in read_files("f1.txt", "f2.txt", "f3.txt"):
        #... do whatever with the line
    

    or

    filenames = ["f1.txt", "f2.txt", "f3.txt"]
    for line in read_files(*filenames):
        #... do whatever with the line
    

提交回复
热议问题