简体   繁体   English

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

[英]Appending Data from Another File to the Beginning of a File

Is there any way to append the content of file1 to the beginning of file2?有没有办法将file1的内容附加到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() 

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更新,因为您需要将 file2 附加到 file1 的开头,请执行

string3 = string2 + " " + string1

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM