-2

I wanted to combine two .txt files into another self-generated .txt file

Example:-

Contents of File 1

abcdefg

Contents of file 2

123456

Self-generated .txt File in the output folder

abcdefg
123456

filenames = [fname1, fname2, fname3]
with open('H:\output\output.txt', 'w') as outfile:
    for fname in filenames:
        with open(fname) as infile:
            for line in infile:
                outfile.write(line)  

i use this code where it can combine both and write the output but the problem is it is not auto-generated file, we have to personally create an output file

  • 1
    Possible duplicate of [Python concatenate text files](https://stackoverflow.com/questions/13613336/python-concatenate-text-files) – G. Anderson Mar 19 '19 at 19:48
  • 1
    I suggest you break the problem down into smaller parts. For example, to accomplish this task, you need to open a file and read from it. You also need to open another file and write to it. If you don't know how to do either of these in Python, then you should google something like "read file python" or "write file python" for more information. – Code-Apprentice Mar 19 '19 at 19:50
  • @Code-Apprentice no that is not the case, I have to generate a new text file by itself by adding the contents of both the file, I lack in knowledge of generating a new file by itself by adding contents of those two files –  Mar 19 '19 at 19:53
  • 1
    Had you done the research that Code-Apprentice suggested, you would have found your problem entirely solved by opening a file in write mode. There is nothing different about your question that cannot, unless you're missing details, be solved by that approach. – roganjosh Mar 19 '19 at 19:57
  • 1
    @Appries what do you mean by generating a new file by itself? You mention auto-generating a file, is that any different? Do you want your program/script to know the name of the output file? – simplycoding Mar 19 '19 at 20:01
  • @roganjosh thank youuuuu.... i totally forgot i can create a .txt and then write the output file into it. –  Mar 19 '19 at 20:04
  • @simplycoding im sorry, i dint get the word create, by auto-generated i meant create a new file –  Mar 19 '19 at 20:05
  • @Code-Apprentice, you are right, I totally forgot that I could create a new file –  Mar 19 '19 at 20:17

1 Answers1

0

This works perfectly – just change the file1.txt and file2.txt lines to fit the filenames of your two files if you'd like:

# Open both .TXT files
file1 = open("file1.txt", "r")
file2 = open("file2.txt", "r")

# Read both .TXT files and put contents into variables
file1Contents = file1.read()
file2Contents = file2.read()

# Close both files
file1.close()
file2.close()

# Open new .TXT file for the resulting concatenated file
resultFile = open("result.txt","w")

# Write concatenated contents to resulting file
resultFile.write(file1Contents + file2Contents)

# Close resulting file
resultFile.close()