myfatson
myfatson

Reputation: 549

How to print a multiline string to a file with variables?

Data: [redacted]

I'm new to python (only know R) and I'm attempting to do a rather trivial task but can't figure it out.

I'm trying to format a table in python that looks like this:

  Financial Analysis
  ----------------------------
  Total Months: 86
  Total: $38382578
  Average  Change: $-2315.12
  Greatest Increase in Profits: Feb-2012 ($1926159)
  Greatest Decrease in Profits: Sep-2013 ($-2196167)

I've managed to recreate it with this code:

print(f"""
{line1}
{line2}
{line3}
{line4}
{line5}
{line6}
{line7}
""")


Financial Analysis
----------------------------
Total Months: 86
Total: $38382578
Average Change: $-2315.12
Greatest Increase in Profits: Feb-2012 ($1926159)
Greatest Decrease in Profits: Sep-2013 ($-2196167)


Full preceding code:

#Import data
df = pandas.read_csv('Resources/budget_data.csv')
df.head()

date = df['Date'].count()
sum_profit_losses = df['Profit/Losses'].sum()
avg_change = round(df['Profit/Losses'].diff().mean(),2)
df['change'] = df['Profit/Losses'].diff()
greatest_increase = df.sort_values(by="change", ascending=False).iloc[0,0:3]
greatest_decrease = df.sort_values(by="change").iloc[0,0:3]

line1 = "Financial Analysis".format()
line2 = "----------------------------".format()
line3 = "Total Months: {}".format(date)
line4 = "Total: ${}".format(sum_profit_losses)
line5 = "Average Change: ${}".format(avg_change)
line6 = "Greatest Increase in Profits: {a} (${b})".format(a=greatest_increase["Date"], b=round(greatest_increase["change"])) 
line7 = "Greatest Decrease in Profits: {a} (${b})".format(a=greatest_decrease["Date"], b=round(greatest_decrease["change"])) 

a = print(f"""
{line1}
{line2}
{line3}
{line4}
{line5}
{line6}
{line7}
""")

The problem is, the whenever I put my string into print to get a multiline statement, it results as a "NoneType" so whatever method I attempt to use to write it out to a file fails. I have confirmed that each individual variable (line1, line2, etc.) are all str types but once I put this into a print statement it throws everything off due to the "NoneType".

What's the correct way to do this?

Edit: Final Correct Code:

import pandas
df = pandas.read_csv('Resources/budget_data.csv')
date = df['Date'].count()
sum_profit_losses = df['Profit/Losses'].sum()
avg_change = round(df['Profit/Losses'].diff().mean(),2)
df['change'] = df['Profit/Losses'].diff()
greatest_increase = df.nlargest(1, 'change')
greatest_decrease = df.nsmallest(1,'change')
line1 = "Financial Analysis"
line2 = "----------------------------"
line3 = f"Total Months: {date}"
line4 = f"Total: ${date}"
line5 = f"Average Change: ${avg_change}"
line6 = f"Greatest Increase in Profits: {greatest_increase['Date'].item()} ${round(greatest_increase['change'].item())}"
line7 = f"Greatest Decrease in Profits: {greatest_decrease['Date'].item()} ${round(greatest_decrease['change'].item())}"
s = f"""
{line1}
{line2}
{line3}
{line4}
{line5}
{line6}
{line7}
"""
print(s)
with open("output.txt", "w") as f:
    f.write(s)

Financial Analysis
----------------------------
Total Months: 86
Total: $86
Average Change: $-2315.12
Greatest Increase in Profits: Feb-2012 $1926159
Greatest Decrease in Profits: Sep-2013 $-2196167

Upvotes: 1

Views: 119

Answers (2)

TheEagle
TheEagle

Reputation: 5992

print(...) returns None. Assign your multiline f-string to a variable, which you then can print out to the console and write it to a file:

date = df['Date'].count()

line1 = "Financial Analysis"
line2 = "----------------------------"
line3 = f"Total Months: {date}"

s = f"""
{line1}
{line2}
{line3}
""")
print(s)
with open("some/file.txt", "w") as f:
    f.write(s)

Upvotes: 3

godot
godot

Reputation: 3545

total_month = 86
total = 38382578
average_change = -2315.12
greatest_increase_in_profits = 1926159
greatest_decrease_in_profits = -2196167

string = """Financial Analysis
  ----------------------------
  Total Months: {0}
  Total: ${1}
  Average  Change: ${2}
  Greatest Increase in Profits: Feb-2012 (${3})
  Greatest Decrease in Profits: Sep-2013 (${4})""".format(total_month, total, average_change, greatest_increase_in_profits, greatest_decrease_in_profits)
print(string)

Output:

Financial Analysis
  ----------------------------
  Total Months: 86
  Total: $38382578
  Average  Change: $-2315.12
  Greatest Increase in Profits: Feb-2012 ($1926159)
  Greatest Decrease in Profits: Sep-2013 ($-2196167)

Upvotes: 0

Related Questions