Load folder files and write them to a file?

0

I would like to know what the script is like to read all the files in a folder and put all the lines together (copy them) into a new file and at the beginning of each line the name of the separate source file appears with a space of the content of the line, example:

archivo1 Hola este es un ejemplo
archivo1 de lo que necesito
archivo2 no puedo usar scripts dificiles
archivo3 ni complicados, ya que no me han enseñado nada dificil en particular
archivo4 ediubewfpqgf9834gr2930r
archivo5 no sé hacerlo, gracias
    
asked by Weketee 30.11.2018 в 19:15
source

1 answer

2

You could list the files in a directory with

import os
root_dir = "my_directorio"

files = os.listdir(root_dir)

You could iterate the list of files and read the contents of each file with

content  = open(file[0], “mode”).read();

And you could write write the content in each iteration cycle with

final_file = open(“final.txt”,”w”)
final_file.write(file[0] + content)

I leave you the task of joining everything in a single snippet:)

    
answered by 30.11.2018 в 20:02