簡體   English   中英

我想知道如何合並 function

[英]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.

這是“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):

我想用兩個參數定義“合並”功能。 第一個參數是輸入文件的名稱(字符串列表),第二個參數是字符串的名稱 output 文件(字符串)。 此時,這個function中沒有output。 第一個參數由列表組成。 現在,我目前傾向於 'open("filename","r"),strip(),close(),readlines()' function。 所以,我想使用這個 function 合並 function。

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

當我寫這篇文章時,我希望將上面的文本結合起來。 請幫我。

您需要像這樣編寫一個 function ,它接受文件名列表並遍歷所有文件名並讀取文件的所有內容。 之后我添加了新行,以確保第一個文件的內容在第二個文件的內容之前有一行空格。 如果你願意,你可以刪除它。

最后,您將該字符串寫入另一個文件。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM