Search code examples
pythontextprepend

Compact way of pre-pending mutiple text files in python


a bit of a silly question. I am trying to insert (prepend) multiple text files (apple, banana, pear) into a main text file (fruitsalad.txt). How do a make this more concise? (PS there is more fruit than what I am showing!)

input01 = path_include + 'apple.txt'
input02 = path_include + 'banana.txt'
input03 = path_include + 'pear.txt'

prepend01 = open(input01,'r').read()
prepend02 = open(input02,'r').read()
prepend03 = open(input03,'r').read()

open(fruitsalad_filepath, 'r+').write(prepend01+prepend02+prepend03 + open(fruitsalad_filepath).read())

Solution

  • Assuming you have some list

    fruit = ['apple.txt', 'banana.txt', 'pear.txt']
    

    you can open the target file, then write the contents of each fruit file across one at a time

    with open(fruitsalad_filepath, 'w+') as salad:
        for item in fruit:
            with open(path_include+item) as f:
                salad.write(f.read())
    

    Doing it this way means you don't have to save the text in intermediate variables, which could eat up a lot of memory. Also, you should read up on the use of context managers in python (the with ... as ... : statements)