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

前端 未结 8 2402
迷失自我
迷失自我 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:29

    Use input from fileinput module. It reads from multiple files but makes it look like the strings are coming from a single file. (Lazy line iteration).

    import fileinput
    
    files= ['F:/files/a.txt','F:/files/c.txt','F:/files/c.txt']
    
    allfiles = fileinput.input(files)
    
    for line in allfiles: # this will iterate over lines in all the files
        print(line)
    
    # or read lines like this: allfiles.readline()
    

    If you need all the text in one place use StringIO

    import io
    
    files= ['F:/files/a.txt','F:/files/c.txt','F:/files/c.txt']
    
    
    lines = io.StringIO()   #file like object to store all lines
    
    for file_dir in files:
        with open(file_dir, 'r') as file:
            lines.write(file.read())
            lines.write('\n')
    
    lines.seek(0)        # now you can treat this like a file like object
    print(lines.read())
    

提交回复
热议问题