每次迭代函数都会覆盖数据帧

时间:2021-06-24 14:09:15

标签: python pandas dataframe

所以我将多个 docx 文件转换为数据帧文件。该代码适用于一个文档,这导致以下结构:

data = {'Title': ['title first article, 'title second article'], 'Sources': ['source of first article', 'source of second article']}
df = pd.DataFrame(data=data)

结构是函数的结果:

def func_convert_updates(filename):
    path = os.chdir('C:/Users/docxfiles')
    regex = '\xc2\xb7'
    with open(filename, "rb") as docx_file:
        result = mammoth.convert_to_html(docx_file)
        text = result.value # The raw text
        text2=re.sub(u'[|•●]', " ", text, count= 0) 
        with open('output.txt', 'w', encoding='utf-8') as text_file:
            text_file.write(text2)

    #followed by many lines of code, omitted here, to create a dataframe

    return df_titles

然后我想分析多个 docx 文件,因此我编写了以下代码:

list_news= ['docx_file_1', 'docx_file_2.docx', ... etc]

for element in list_news:
    df_titles = func_convert_updates(element)

然而,这只会返回列表最后一个元素的数据帧,因为它会覆盖之前的输出。我该如何解决这个问题?提前致谢。

2 个答案:

答案 0 :(得分:1)

如果您想将在每个循环中创建的所有数据帧都放在变量 df_titles 中,您可以执行以下操作:

import pandas as pd

df_titles = pd.concat([func_convert_updates(element) for element in list_news], ignore_index=True)

答案 1 :(得分:0)

实际问题是,如果您多次调用函数,您会告诉 open 写入 'output.txt' 文件,如果文件存在,则使用 'w' 参数覆盖该文件。您可能希望将其更改为 'a' 以附加到文件中,因此:

with open('output.txt', 'a', ...

另见 https://cmdlinetips.com/2012/09/three-ways-to-write-text-to-a-file-in-python/