我想知道如何制作合并功能

问题描述 投票:0回答:1
File1: Pusan National University was founded in May 1946 with
the establishment ideology of truth, liberty and devotion.

这是“ pnu1.txt”

File 2: Although the University started initially with just two faculties, the Faculty of Humanities and the Faculty of Fisheries, since then, it has grown into a major research level institution covering all the major disciplines within academia. Today, the University enjoys its reputation as one of top universities in Korea.

这是“ pnu2.txt”

File 3: The University now compriseds fifteen colleges, one independent division, one general graduate school, fourprofessional graduate schools and five special graduate schools, and contributes to the development of the nation by producing prominent experts and talented leaders.

这是“ pnu3.txt”

def merge(list_of_string,string):

我想用两个参数定义'合并'功能。第一个参数是输入文件的名称(字符串列表),第二个参数是字符串输出文件的名称(字符串)。此时,此功能无输出。第一个参数由列表组成。现在,我目前正在使用'open(“ filename”,“ r”),strip(),close(),readlines()'函数。因此,我想使用此功能制作合并功能。

merge(["pnu1.txt","pnu2.txt","pnu3.txt"],"result.txt")

[在撰写本文时,我希望将以上文本进行合并。请帮助我。

python merge pycharm
1个回答
0
投票

您需要编写一个像这样的函数,该函数接受文件名列表并遍历所有文件名并读取文件的所有内容。之后,我添加了新行,以确保第一个文件的内容在第二个文件的内容之前有一行空格。您可以根据需要将其删除。

最后,您将该字符串写入另一个文件。

def merge(fileNames, resultFile):
    str = ""
    for file in fileNames:
        str += open(file).read()
        str += '\n'
    open(resultFile, 'w').write(str)
© www.soinside.com 2019 - 2024. All rights reserved.