I'm exporting some data in my python script to an Excel file and I am wondering if I can also export the contents of the currently-running script to that Excel file. This would save me time so that I do not have to manually copy my script to that Excel file each time I run it.
I have no problems writing to Excel, my only problem is that I do not know if python can write out its own script contents.
import pandas
excel_file = pandas.ExcelFile("my_file.xlsx")
df = excel_file.parse("sheet_name")
data = df.sample(n=5, random_state=1)
# I would prefer to get the script contents here
# script_contents = ?
with pandas.ExcelWriter("output.xlsx") as writer:
data.to_excel(writer, sheet_name='Data')
script_contents.to_excel(writer, sheet_name='Script')
EDIT: The possible duplicate isn't a total solution since it only returns a string and my problem needs a DataFrame of the source code. See my solution in the answers below.