首页 > 解决方案 > Pandas & Python:有没有办法导入excel文件的内容,在文件末尾添加文本内容,然后保存下来?

问题描述

我有一个存储在 excel 文件中的名称列表。用户需要能够导入该列表,这是一个单列,并向列表中添加其他名称,并保存文件。

我已经使用 pandas 导入了 excel 文件并创建了一个数据框(df)。我尝试使用循环函数附加 df 。

import numpy as np
import pandas as pd

path = 'C:\\NY_Operations\\EdV\\Streaman\\Python\\CES Fee Calc\\'
file_main = 'Main.xlsx'
df_main = pd.read_excel(path + file_main)

while True:
    b = (input("Enter name of new deal to be added to 'Main' spreadsheet or type 'Exit' "))
    df_main.append(b)
    if df_main [-1] == "Exit":
        df_main.pop()
        break

电子表格在 A1、A2 和 A3 中有“玩具”、“颜色”、“球”。应提示用户添加新交易,他/她添加“Watch”和“Belt”,然后写入“Exit”,循环结束。在电子表格中,A4 应显示“Watch”,A5 应在 df 和电子表格中显示“Belt”。

标签: pythonpandas

解决方案


我能够弄清楚。感谢大家的帮助。

import numpy as np
import pandas as pd

#create list of deals in the 'main' consolidation spreadsheet

path = 'C:\\NY_Operations\\EdV\\Streaman\\Python\\CES Fee Calc\\'
file_main = 'Main.xlsx'

df_main = pd.read_excel(path + file_main)

new_deals = [] #each entry is the name of the item purchased

while True:
    g = (input("Enter name of item or exit "))
    new_deals.append(g)
    if new_deals [-1] == "exit":
        new_deals.pop()
        break
df_newdeals = pd.DataFrame({'Deal Name':new_deals})

df1 = pd.concat([df_main,df_newdeals])

print(df1)
df1.to_excel(path + file_main)

推荐阅读