Python 将另一个文件中的数据追加到文件的开头

Python 将另一个文件中的数据追加到文件的开头,python,file,append,Python,File,Append,有没有办法将文件1的内容附加到文件2的开头?我试过用这种方法,但似乎不起作用 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

有没有办法将文件1的内容附加到文件2的开头?我试过用这种方法,但似乎不起作用

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() 

首先,您需要将这些文件的内容分配到变量中

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()
然后与
+
运算符组合

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

更新,因为需要将文件2追加到文件1的开头, 做

请尝试以下代码:

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()

这回答了你的问题吗?
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()