简体   繁体   中英

I want to know how to make merge function

File1: Pusan National University was founded in May 1946 with
the establishment ideology of truth, liberty and devotion.

This is "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.

This is "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.

And This is "pnu3.txt"

def merge(list_of_string,string):

I want to make 'merge' fuction defined with two parameters. 1st parameter is names of input files(list of string),2nd parameters are name of a string output file(string). At this time, no output in this function. And 1st parameter consist of list. Now, I am currently leaning 'open("filename","r"),strip(),close(),readlines()' function. So, I want to make merge function using this function.

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

When I write this, I want the texts above to be combined. Please help me.

You need to write a function like this which accepts a list of fileNames and loop over all the filenames and read all the content of files. I have added new line after that to make sure the first file's content have one line of space before second file's content. You can remove that if you wish.

And at last, you write that string to another file.

def merge(fileNames, resultFile):
    str = ""
    for file in fileNames:
        str += open(file).read()
        str += '\n'
    open(resultFile, 'w').write(str)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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