【问题标题】:Appending Data from Another File to the Beginning of a File将另一个文件中的数据附加到文件的开头
【发布时间】:2021-03-05 04:53:36
【问题描述】:

有没有办法将file1的内容附加到file2的开头?我试过用这个方法,但它似乎不起作用

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

【问题讨论】:

标签: python file append


【解决方案1】:

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

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

完成。

更新,因为您需要将file2附加到file1的开头, 做

string3 = string2 + " " + string1

【讨论】:

    【解决方案2】:

    试试这个代码:

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

    【讨论】:

      猜你喜欢
      • 2011-07-05
      • 2019-08-15
      • 1970-01-01
      • 2018-12-06
      • 1970-01-01
      • 2015-10-17
      • 2014-02-26
      • 2011-07-24
      • 2018-01-09
      相关资源
      最近更新 更多