我正在尝试使用 pandas 更新我的 excel 文件,但每次文件都会损坏,我无法再打开它 1234.xlsx -> Sheet1 gammagammasatE50refEoedRefEurRefcΦEAf.s 17.6718.6...
我正在尝试使用 pandas ,但每次文件都会损坏,我无法再打开它
伽马 | 伽玛卫星 | E50参考 | 参考文献 | 欧洲参考文献 | 丙 | F | EA | 文件系统 |
---|---|---|---|---|---|---|---|---|
17.67 | 18.6 | 10500 | 10500 | 36000 | 4 | 24 | 4800 | |
17.67 | 18.6 | 10500 | 10500 | 36000 | 4 | 三十六 | 7200 |
所以我想用 python 代码填充 fs 列,并在计算后立即写入每行的答案
import pandas as pd
import os
file_name = "1234.xlsx"
file_path =os.path.join(os.getcwd(),file_name)
df = pd.read_excel(file_path)
for index, row in df.iterrows():
gammaUnsat = row['gammaUnsat']
gammaSat = row['gammasat']
E50ref = row['E50ref']
EoedRef = row['EoedRef']
EurRef = row['EurRef']
c = row['c']
phi = row['Φ']
EA = row['EA']
# some calculation
#code to write in file
df.loc[index , "f.s"] = sf_i
writer = pd.ExcelWriter(path=file_path,engine="xlsxwriter")
df.to_excel(writer,"Sheet1",index=False)
我没有遇到任何错误,程序运行正常,但当我点击 Excel 文件时,它告诉我文件已损坏
你必须关闭 writer,这样你的代码就会像这样
import pandas as pd
import os
file_name = "1234.xlsx"
file_path =os.path.join(os.getcwd(),file_name)
df = pd.read_excel(file_path)
for index, row in df.iterrows():
gammaUnsat = row['gammaUnsat']
gammaSat = row['gammasat']
E50ref = row['E50ref']
EoedRef = row['EoedRef']
EurRef = row['EurRef']
c = row['c']
phi = row['Φ']
EA = row['EA']
# some calculation
#code to write in file
df.loc[index , "f.s"] = sf_i
writer = pd.ExcelWriter(path=file_path,engine="xlsxwriter")
df.to_excel(writer,"Sheet1",index=False)
writer.close()
或将 pandas 导入为 pdimport osfile_name = \'1234.xlsx\'file_path =os.path.join(os.getcwd(),file_name)
df = pd.read_excel(file_path)
for index, row in df.iterrows():
gammaUnsat = row['gammaUnsat']
gammaSat = row['gammasat']
E50ref = row['E50ref']
EoedRef = row['EoedRef']
EurRef = row['EurRef']
c = row['c']
phi = row['Φ']
EA = row['EA']
# some calculation
#code to write in file
df.loc[index , "f.s"] = sf_i
with pd.ExcelWriter(file_path,engine='xlsxwriter') as writer:
df.to_excel(excel_writer=writer,sheet_name="Sheet1",index=False)
我认为您可以创建描述符并在循环中随时打开/关闭文件(ps 我没有测试代码)但可能有效
import pandas as pd
import os
file_name = "1234.xlsx"
file_path = os.path.join(os.getcwd(), file_name)
df = pd.read_excel(file_path)
for index, row in df.iterrows():
gammaUnsat = row['gammaUnsat']
gammaSat = row['gammasat']
E50ref = row['E50ref']
EoedRef = row['EoedRef']
EurRef = row['EurRef']
c = row['c']
phi = row['Φ']
EA = row['EA']
# some calculation
#code to write in file
df.loc[index, "f.s"] = sf_i
writer = pd.ExcelWriter(file_path, engine="xlsxwriter")
df.to_excel(writer, "Sheet1", index=False)
writer.save()