串联 python 中的两个文件

Concatenation two files in python

我有以下读取文件的函数,然后将它们存储在变量中:

def browseFiles():
    filename = filedialog.askopenfilename(initialdir = "/home",
                                          title = "Select a File",
                                          filetypes = (("Text files",
                                                        "*.docx*"),
                                                       ("all files",
                                                        "*.*")))
    label_file_explorer.configure(text="File Opened: "+ filename)
    with open(filename) as fp:
     firstfile = fp.read()

def browseFiles1():
    filename1 = filedialog.askopenfilename(initialdir = "/home",
                                          title = "Select a File",
                                          filetypes = (("Text files",
                                                        "*.docx*"),
                                                       ("all files",
                                                        "*.*")))
    label_file_explorer.configure(text="File Opened: "+ filename1)
    with open(filename1) as fp:
     secondfile = fp.read()

我想将第一个文件和第二个文件连接在一起,然后生成第三个文件。所以,我用了:

firstfile += "\n"
firstfile += secondfile
  
with open ('thirdfile.docx', 'w') as fp:
    fp.write(firstfile)

我的问题是如何访问每个函数中的变量 firstfile 和 secondfile 并使用它们生成第三个文件?

您可以 return 来自这两个函数的文件内容,这就是您从“主函数”访问这两个函数的方式。

您必须 return 来自 2 个函数的 firstfilesecondfile,将它们存储在变量中,然后使用 pd.concat 函数。

def browseFiles():
    filename = filedialog.askopenfilename(initialdir = "/home",
                                          title = "Select a File",
                                          filetypes = (("Text files",
                                                        "*.docx*"),
                                                       ("all files",
                                                        "*.*")))
    label_file_explorer.configure(text="File Opened: "+ filename)
    with open(filename) as fp:
     firstfile = fp.read()

    return firstfile


def browseFiles1():
    filename1 = filedialog.askopenfilename(initialdir = "/home",
                                          title = "Select a File",
                                          filetypes = (("Text files",
                                                        "*.docx*"),
                                                       ("all files",
                                                        "*.*")))
    label_file_explorer.configure(text="File Opened: "+ filename1)
    with open(filename1) as fp:
     secondfile = fp.read()
    
    return secondfile

firstfile = browseFiles()
secondfile = browseFiles1()

thirdfile = pd.concat([firstfile, secondfile])

这是 concat 文档的link

干杯!