0

Is there any way to append the content of file1 to the beginning of file2? I tried using this method but it doesn't seem to work

def main():
    """The program does the following:
    - it inserts all the content from file2.txt to the beginning of file1.txt
    
    Note: After execution of the your program, only file1.txt is updated, file2.txt does not change."""
    #WRITE YOUR PROGRAM HERE

    

#Call the main() function
if __name__ == '__main__':
    main()
    f = open('file1.txt', 'r')
    f1 = open('file2.txt', 'r')
    def insert(file2, string):
        with open('file2.txt','r') as f:
            with open('file1.txt','w') as f1: 
                f1.write(string)
                f1.write(f.read())
        os.rename('file1.txt',file2)
    
    # closing the files 
    f.close() 
    f1.close() 
nzt2106
  • 1
  • 1
  • Does this answer your question? [Prepend line to beginning of a file](https://stackoverflow.com/questions/5914627/prepend-line-to-beginning-of-a-file) – Shane Richards Nov 22 '20 at 08:35

2 Answers2

0

Firstly, you need to assign those files' content into variables.

string1 = ""
string2 = ""
with open('file1.txt', 'r') as file:
    string1 = file.read().replace('\n', '')
    file.close()

with open('file2.txt', 'r') as file:
    string2 = file.read().replace('\n', '')
    file.close()

and then combine with + operator

string3 = string1 + " " + string2
with open("file3.txt", "w") as file:
    text_file.write("%s" % string3)
    file.close()

done.

Update, as you need to append file2 into the beginning of file1, do

string3 = string2 + " " + string1
apridos
  • 172
  • 4
0

Try this code:

data = open("file.txt", "r").read()
data = data.split("\n")
new_data = #what you want to add
new_data = new_data.split("\n")
for elem in new_data:
    data.insert(0, elem)
f = open("file.txt", "a")
f.truncate()
for elem in data:
    f.write(elem)
f.close()
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Leonardo Scotti
  • 1,069
  • 8
  • 21