Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

file

This question is related to Python concatenate text files

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

I would like to open all the files into a single file object that I can read through line by line, but I don't want to create a new file in the process. Is that possible?

with open(file_names, 'r') as file_obj:
   line = file_obj.readline()
   while line:
       ...
like image 422
bluprince13 Avatar asked Sep 15 '17 10:09

bluprince13


People also ask

How do I put multiple files into one file?

Go to File > New Document. Choose the option to Combine Files into a Single PDF. Drag the files that you want to combine into a single PDF into the file-list box. You can add a variety of file types, including PDFs, text files, images, Word, Excel, and PowerPoint documents.

How do I combine multiple text files into one?

Two quick options for combining text files.Open the two files you want to merge. Select all text (Command+A/Ctrl+A) from one document, then paste it into the new document (Command+V/Ctrl+V). Repeat steps for the second document. This will finish combining the text of both documents into one.

How concatenate multiple files in Linux?

Type the cat command followed by the file or files you want to add to the end of an existing file. Then, type two output redirection symbols ( >> ) followed by the name of the existing file you want to add to.


2 Answers

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())
like image 132
Anonta Avatar answered Sep 19 '22 12:09

Anonta


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
like image 29
Lohmar ASHAR Avatar answered Sep 19 '22 12:09

Lohmar ASHAR