Home > Net >  Using Python to copy contents of multiple files and paste in a main file
Using Python to copy contents of multiple files and paste in a main file

Time:05-19

I'll start by mentioning that I've no knowledge in Python but read online that it could help me with my situation.

I'd like to do a few things using (I believe?) a Python script. I have a bunch of .yml files that I want to transfer the contents into one main .yml file (let's call it Main.yml). However, I'd also like to be able to take the name of each individual .yml and add it before it's content into Main.yml as "##Name". If possible, the script would look like each file in a directory, instead of having to list every .yml file I want it to look for (my directory in question only contains .yml files). Not sure if I need to specify, but just in case: I want to append the contents of all files into Main.yml & keep the indentation (spacing). P.S. I'm on Windows

Example of what I want:

  • File: Apes.yml
  • Contents:
Documentation:
  "Apes":
    year: 2009
    img: 'link'

After running the script, my Main.yml would like like:

##Apes.yml
Documentation:
  "Apes":
    year: 2009
    img: 'link'

CodePudding user response:

I'm just starting out in Python too so this was a great opportunity to see if my newly learned skills work!

I think you want to use the os.walk function to go through all of the files and folders in the directory.

This code should work - it assumes your files are stored in a folder called "Folder" which is a subfolder of where your Python script is stored

# This ensures that you have the correct library available
import os

# Open a new file to write to
output_file = open('output.txt','w ')

# This starts the 'walk' through the directory
for folder , sub_folders , files in os.walk("Folder"):

    # For each file...
    for f in files:
        # create the current path using the folder variable plus the file variable
        current_path = folder "\\" f

        # write the filename & path to the current open file
        output_file.write(current_path)

        # Open the file to read the contents
        current_file = open(current_path, 'r')

        # read each line one at a time and then write them to your file
        for line in current_file:
            output_file.write(line)

        # close the file
        current_file.close()

#close your output file
output_file.close()
  • Related