If you want to join the contents of multiple text files in memory use a text stream io.StringIO()
.
The content of io.StringIO()
may be written with the inherited method io.TextIOBase.write()
or with the built-in function print()
setting the parameter file
with the stream.
The content of io.StringIO()
can be read in a string with the method io.StringIO.getvalue()
.
To execute a code dynamically use the built-in function exec
.
The example below presupposes the use of three text files that together compose a script:
script.py1
texto = 'Hello, world!'
script.py2
def foo(s):
print(f'foo {s}')
script.py3
foo(texto)
The python script that will read the three files, join its contents and dynamically execute the generated script:
import io
#Inicializa stream de texto a ser preenchida com conteúdo dos arquivos.
f = io.StringIO()
#Abre, lê e junta os conteúdos dos arquivos na memória.
with open('script.py1') as script:
print(*script.readlines(), file=f)
with open('script.py2') as script:
print(*script.readlines(), file=f)
with open('script.py3') as script:
print(*script.readlines(), file=f)
#Obtem uma string com o conteúdo unificado dos arquivos.
arquivo = f.getvalue()
#Fecha a stream.
f.close()
#Executa o arquivo no contexto local.
exec(arquivo, globals(), locals()) #foo Hello, world!
Test the example on Repl.it
I don’t understand the question. You want to do this https://ideone.com/RJ8nNn read several files join the texts in memory and run the resulting script?
– Augusto Vasques
That’s right, !!!
– GAB