Search code examples
pythonlistfor-loopwith-statement

How to combine function with a list in python?


I want to combine out_fun() to combinefiles(). Currently I have it where out_fun() it writes to file3.txt and then closes it. Next, I have it where out_fun() is called within combinefiles() to write "Hello World" in order to combine out_fun() with combinefiles(). This solution is not working because it ends up printing hello world three separate times in the Python Shell and just says "None" within the file3.txt file. I'm wondering how I can do this so it doesn't make this so it doesn't print "Hello World" three times as I want it only to be printed once like in out_fun() and then I want "Hello World" added to the bottom of combinefiles()

def out_fun(): 
    print("Hello World")
output = out_fun() 
file = open("file3.txt","w") 
file.write(str(output))
file.close() 

def combinefiles():
    filenames = ['file1.txt', 'file2.txt']
        with open('file3.txt', 'w') as outfile:
            for names in filenames:
                with open(names) as infile:
                    outfile.write(infile.read())
                    outfile.write("\n")
                    output = out_fun()
                    outfile.write(str(output))
        outfile.close()
combinefiles()

Solution

  • I thnk something like this is what you are looking for. with open(file_path, "a") if you want to continue to add to the bottom of the text file every time you run the code. otherwise just use a w with open(file_path, "w")

    output = "Hello World!"
    file_names = ["file1.txt", "file2.txt", "file3.txt"]
    def combine_files(file_names, output):
        for file_path in file_names:
            with open(file_path, "a") as file:
                file.write(output)
    
            
    combine_files(file_names, output)