Data does not print into the file, resulting in a empty file - python
I've been trying to have this data write to the "scenario_out.txt" file. However, when I run the code I do not any get errors but my text file does come out to empty, so no data was ever put into the file. . I'm reviewing my notes but I don't see where I went wrong.
# Display results of scenario
def file_save_flow(save_to_file, # save to a file object if save_to_file = True
file_object, # name of file object to save to
scen_year,
age,
s_bal,
bal_pv,
inv_gains,
ann_savings,
ss_payment,
major_inc,
major_exp,
tax_rate,
tar_ret_spend,
net_ret_spend,
ret_pre_tax_spend,
taxes,
end_bal
):
""" file_save_flow() test output
>>> out_file = open("scenario_out.txt","w")
>>> file_save_flow(save_to_file = True,
... file_object = out_file,
... scen_year = 0,
... age = 60,
... s_bal = 100000,
... bal_pv = 100000,
... inv_gains = 1000,
... ann_savings = 1000,
... ss_payment = 1000,
... major_inc = 1000,
... major_exp = 1000,
... tax_rate = 0.15,
... tar_ret_spend = 50000,
... net_ret_spend = 40000,
... ret_pre_tax_spend = 60000,
... taxes = 10000,
... end_bal = 120000
... )
>>> out_file.close()
>>> in_file = open("scenario_out.txt","r")
>>> print(in_file.read())
Year :0
Age :60
Start Bal :100,000.00
Start Bal PV :100,000.00
Invest Gains :1,000.00
Ann Savings :1,000.00
SS Payment :1,000.00
Major Inc :1,000.00
Major Exp :1,000.00
Tax Rate :15.00%
Targ Ret Spend :50,000.00
Net Ret Spend :40,000.00
Ret Pre-tax Spend:60,000.00
Taxes :10,000.00
End Bal :120,000.00
<BLANKLINE>
>>> in_file.close()
"""
#=============================My Code================================
if save_to_file == True:
print(' Year :' , scen_year,
'\n Age :',age,
'\n Start Bal :', (format(s_bal, ',.2f')) ,
'\n Start Bal PV :', (format(bal_pv, ',.2f')),
'\n Invest Gains :', (format(inv_gains, ',.2f')),
'\n Ann Savings :', (format(ann_savings,',.2f')),
'\n SS Payment :', (format(ss_payment, ',.2f')),
'\n Major Inc :', (format(major_inc, ',.2f')),
'\n Major Exp :', (format(major_exp, ',.2f')),
'\n Tax Rate :', (format(tax_rate, '.2%')),
'\n Targ Ret Spend :', (format(tar_ret_spend, ',.2f')),
'\n Net Ret Spend :', (format(net_ret_spend, ',.2f')),
'\n Ret Pre-tax Spend :', (format(ret_pre_tax_spend, ',.2f')),
'\n Taxes :', (format(taxes, ',.2f')),
'\n End Bal :', (format(end_bal, ',.2f')))
#============================================================================
# test function
out_file = open("scenario_out.txt","w") # set up the file object to write to
file_save_flow(save_to_file = True,
file_object = out_file,
scen_year = 0,
age = 60,
s_bal = 100000,
bal_pv = 100000,
inv_gains = 1000,
ann_savings = 1000,
ss_payment = 1000,
major_inc = 1000,
major_exp = 1000,
tax_rate = 0.15,
tar_ret_spend = 50000,
net_ret_spend = 40000,
ret_pre_tax_spend = 60000,
taxes = 10000,
end_bal = 120000
)
out_file.close()
in_file = open("scenario_out.txt","r") # read back the contents saved to the file
print(in_file.read())
in_file.close()
I've tied some bool variable to use as a flag , but still no luck.
At the moment, you're just printing your output to the console, rather than actually saving it to the file.
You probably want something like
if save_to_file == True:
output = (
' Year : ' + str(scen_year) +
'\n Age : ' + str(age) +
'\n Start Bal : ' + (format(s_bal, ',.2f')) +
'\n Start Bal PV : ' + (format(bal_pv, ',.2f')) +
'\n Invest Gains : ' + (format(inv_gains, ',.2f')) +
'\n Ann Savings : ' + (format(ann_savings,',.2f')) +
'\n SS Payment : ' + (format(ss_payment, ',.2f')) +
'\n Major Inc : ' + (format(major_inc, ',.2f')) +
'\n Major Exp : ' + (format(major_exp, ',.2f')) +
'\n Tax Rate : ' + (format(tax_rate, '.2%')) +
'\n Targ Ret Spend : ' + (format(tar_ret_spend, ',.2f')) +
'\n Net Ret Spend : ' + (format(net_ret_spend, ',.2f')) +
'\n Ret Pre-tax Spend : ' + (format(ret_pre_tax_spend, ',.2f')) +
'\n Taxes : ' + (format(taxes, ',.2f')) +
'\n End Bal : ' + (format(end_bal, ',.2f'))
)
file_object.write(output)
This creates a big string of your output data, then writes it to your file object.
If you remove all the fluff, your code looks exactly like this:
def file_save_flow(save_to_file, file_object, data):
if save_to_file == True:
print('Data: ', data)
out_file = open("scenario_out.txt", "w")
file_save_flow(save_to_file=True, file_object=out_file, data='data')
out_file.close()
in_file = open("scenario_out.txt", "r")
print(in_file.read())
in_file.close()
From that, it's immediately clear that your function does only one thing: it prints something if save_to_file is True and it prints nothing otherwise. It doesn't do anything with file_object.
So, although you create and open a file and pass the file handle to your function, you don't actually use it in the print() statement.
This would work:
def file_save_flow(save_to_file, file_object, data):
if save_to_file == True:
print('Data: ', data, file=file_object)
else:
print('Data: ', data)
Or, to avoiding repeating yourself:
def file_save_flow(save_to_file, file_object, data):
print('Data: ', data, file=file_object if save_to_file else None)
Related
Using 'For Loop' to write data to a file
I am trying to use 'for loop' to write to a file in python dynamically, but I do not know how to calculate to write dynamically. I would appreciate if I get some help on this. def earnings(name, age, salary): AnnualRate = 0.05 outFile = open('yearly_earnings.txt', 'w') outFile.write('Prepared by: Amornchot Singh') outFile.write('Age Salary Total') n = 26 for n in range(66): ageLimit = 65 i = 26 totalEarned = 0 for i in range(ageLimit+1): totalEarned += salary * (1+AnnualRate) print('summary for ' + name) print('Starting salary at age ' + age + ' was ' + salary) print('Salary increases were 5.0% per year') print('Total accumulated earnings by age 65 is {:,.2f}'.format(totalEarned)) print("To view yearly data go to 'yearly_earnings.txt'") print("'Thank you for using the earnings() function.'")
First of all remove all redundant lines of code Call the function Don't forget to close the file after writing something, otherwise it will not save the data in your file Python don't allow to add integer with string so convert the integer into str before concatenating print('Starting salary at age ' + str(age) + ' was ' + str(salary)) Here is full code def earnings(name, age, salary): AnnualRate = 0.05 outFile = open('yearly_earnings.txt', 'w') outFile.write('Prepared by: Amornchot Singh') outFile.write('Age Salary Total') ageLimit = 65 i = 26 totalEarned = 0 for i in range(ageLimit+1): totalEarned += salary * (1+AnnualRate) outFile.close() print('summary for ' + name) print('Starting salary at age ' + str(age) + ' was ' + str(salary)) print('Salary increases were 5.0% per year') print('Total accumulated earnings by age 65 is {:,.2f}'.format(totalEarned)) print("To view yearly data go to 'yearly_earnings.txt'") print("'Thank you for using the earnings() function.'") earnings("Tariq", 20, 500000)
IndexError: list index out of range error on python
This is my code: while True: print("Type 'done' to finish receipts") code=input("Enter item code to add:") items =open("items.txt") quant=input("Quantity:") details = items.read() detailslist = details.split("\n") for a in detailslist: fire = a.split("#") print (fire) b = fire[0] c = fire[1] d = fire[2] dictd = {} dictd[b] = c + ' ' +' Quantity: '+ ' ' + quant +' '+ 'Price:' + d print (dictd) This is in items.txt: A# Almanac2018# 18.30 B# Almanac2020# 23.80 C# Almanac2021# 16.54 D# Almanac2022# 22.25 I am getting this error: Type 'done' to finish receipts Enter item code to add:A Quantity:45 ['A', ' Almanac2018', ' 18.30'] {'A': ' Almanac2018 Quantity: 45 Price: 18.30'} ['B', ' Almanac2020', ' 23.80'] {'B': ' Almanac2020 Quantity: 45 Price: 23.80'} ['C', ' Almanac2021', ' 16.54'] {'C': ' Almanac2021 Quantity: 45 Price: 16.54'} ['D', ' Almanac2022', ' 22.25'] {'D': ' Almanac2022 Quantity: 45 Price: 22.25'} [''] Traceback (most recent call last): File "receipt.py", line 12, in <module> c = fire[1] IndexError: list index out of range I am trying to make a program that makes a receipt of items so if you could provide any code that would be helpful. Any help would be appreciated.
The problem you have in your code is with the empty strings in your items.txt file. When there's an empty string, fire would resolve to [''], which is a list of only 1 item, so you get an error when the code tries to run c = fire[1]. You can add a check to see if it's an empty line or not: for a in detailslist: fire = a.split("#") if len(fire) > 1: print (fire) b = fire[0] c = fire[1] d = fire[2] dictd = {} dictd[b] = c + ' ' +' Quantity: '+ ' ' + quant +' '+ 'Price:' + d print (dictd)
Give a man a fish, feed him for a day... teach a man to fish. So this isn't a fish, but it is a fishing rod (as long as your using Python v3.7 or greater): import pdb #Only need this if python < v3.7 while True: print("Type 'done' to finish receipts") code=input("Enter item code to add:") items =open("items.txt") quant=input("Quantity:") details = items.read() detailslist = details.split("\n") for a in detailslist: fire = a.split("#") print (fire) try: b = fire[0] c = fire[1] d = fire[2] dictd = {} dictd[b] = c + ' ' +' Quantity: '+ ' ' + quant +' '+ 'Price:' + d print (dictd) except: breakpoint() # if Python >= v3.7 pdb.set_trace() # if Python < v3.7 Which means you can see the exact shape and size of "fire" when the error is being caused. Should help your debugging efforts here - and in future when other problems inevitably crop up.
Trying to build a Twitter heatmap in python
I am trying to teach myself Python. This might be a newbie question. This heatmap is one of the projects I've found and am trying to fix to try and learn. This is the code. It's one of three scripts involved with the project. I will post the other two if needed. I keep getting TypeError: Can't convert bytes object to string implicitly from line 156 (fourth line from the bottom). I get no other errors. I'm running it in python 3. I've already made a few corrections to update the code...especially to the print commands. (I added the parentheses) Any help with the error I'm getting would be immensely appreciated. import tweepy from tweepy import Stream from tweepy import OAuthHandler from tweepy.streaming import StreamListener import geopy from geopy.geocoders import Nominatim geolocator = Nominatim() from textblob import TextBlob #declare variables ckey = 'x' csecret = 'x' atoken = 'x' asecret = 'x' OAUTH_KEYS = {'consumer_key':ckey, 'consumer_secret':csecret, 'access_token_key':atoken, 'access_token_secret':asecret} auth = tweepy.OAuthHandler(OAUTH_KEYS['consumer_key'], OAUTH_KEYS['consumer_secret']) api = tweepy.API(auth) #open file saveFile = open('file.csv', 'a') headers = 'Time; User; Text; Sentiment; Question; Place; Latitude; Longitude;' saveFile.write(headers + '\n') #print tweets for tweet in tweepy.Cursor(api.search, q ='#pittsburgh').items(): ''' Parameters (*required): q*: word, hashtag of interest [#hashtag] geocode: returns tweets by users located within a given radius of the given latitude/longitude [37.781157,-122.398720,1km] lang: language [es] result_type: [mixed, popular or recent] count: [15-100] until: YYYY-MM-DD, 7-day limit [2015-12-5] since_id: returns results with an ID greater than (that is, more recent than) the specified ID [12345] ''' if tweet.coordinates: print("===========") #date & time moment = tweet.created_at print('Date & Time: ', moment) #text string = tweet.text.replace('|', ' ') string = tweet.text.replace('\n', ' ') print('Text: ', string.encode('utf8')) #user user = tweet.author.name.encode('utf8') print('User:', user) #sentiment text = TextBlob(string) if text.sentiment.polarity < 0: sentiment = "negative" elif text.sentiment.polarity == 0: sentiment = "neutral" else: sentiment = "positive" print('Sentiment: ', sentiment) #question if '?' in string: question = 'Yes' else: question = 'No' print('Question: ', question) #location place = geolocator.reverse(str(tweet.coordinates)) print('Place: ', place) latitude = tweet.coordinates[0] longitude = tweet.coordinates[1] print('Coords:', tweet.coordinates) print("===========") #save tweets saveThis = str(moment) + '; ' + str(string.encode('ascii', 'ignore')) + '; ' + user + '; ' + sentiment + '; ' + question + '; ' + place + '; ' + str(latitude) + '; ' + str(longitude) + '; ' saveFile.write(saveThis + '\n') if tweet.place: print("===========") #date & time moment = tweet.created_at print('Date & Time: ', moment) #text string = tweet.text.replace('|', ' ') string = tweet.text.replace('\n', ' ') print('Text: ', string.encode('utf8')) #user user = tweet.author.name.encode('utf8') print('User: ', user) #sentiment text = TextBlob(string) if text.sentiment.polarity < 0: sentiment = "negative" elif text.sentiment.polarity == 0: sentiment = "neutral" else: sentiment = "positive" print('Sentiment: ', sentiment) #question if '?' in string: question = 'Yes' else: question = 'No' print('Question: ', question) #location place = tweet.place.full_name print('Place:', place) location = geolocator.geocode(place) latitude = location.latitude longitude = location.longitude print('Coords: ', location.latitude, location.longitude) print("===========") #save tweets saveThis = str(moment) + '; ' + str(string.encode('ascii', 'ignore')) + '; ' + user + '; ' + sentiment + '; ' + question + '; ' + place + '; ' + str(latitude) + '; ' + str(longitude) + '; ' saveFile.write(saveThis + '\n') else: print("===========") #date & time moment = tweet.created_at print('Date & Time', moment) #text string = tweet.text.replace('|', ' ') string = tweet.text.replace('\n', ' ') print('Text:', string.encode('utf8')) #user user = tweet.author.name.encode('utf8') print('User:', user) #sentiment text = TextBlob(string) if text.sentiment.polarity < 0: sentiment = "negative" elif text.sentiment.polarity == 0: sentiment = "neutral" else: sentiment = "positive" print('Sentiment:', sentiment) #question if '?' in string: question = 'Yes' else: question = 'No' print('Question:', question) #location place = '' latitude = '' longitude = '' print('Place:', place) print('Coords:', latitude, longitude) print("===========") #save tweets saveThis = str(moment) + '; ' + str(string.encode('ascii', 'ignore')) + '; ' + user + '; ' + sentiment + '; ' + question + '; ' + place + '; ' + str(latitude) + '; ' + str(longitude) + '; ' saveFile.write(saveThis + '\n') #close file saveFile.close()
Getting easygui to self update info
Trying to get a self updating speedometer and clock working for my truck using gps. So far I have been able to get the read out that I want using easygui and msgbox but it is not self updating which will not help much on either application. Below is the code. Any help would be much appreciated, I know this is pretty ugly and probably not correct but I am new to python. import gps from easygui import * import sys # Listen on port 2947 (gpsd) of localhost session = gps.gps("localhost", "2947") session.stream(gps.WATCH_ENABLE | gps.WATCH_NEWSTYLE) while True: try: report = session.next() if report['class'] == 'TPV': if hasattr(report, 'time'): hour = int(report.time[11:13]) hourfix = hour - 7 if hourfix < 12: time = 'Current Time Is: ' + report.time[5:7] + '/' + report.time[8:10] + '/' + report.time[0:4] + ' ' + str(hourfix) + report.time[13:19] + ' am' else: hourfix = hourfix - 12 time = 'Current Time Is: ' + report.time[5:7] + '/' + report.time[8:10] + '/' + report.time[0:4] + ' ' + str(hourfix) + report.time[13:19] + ' pm' if report['class'] == 'TPV': if hasattr(report, 'speed'): speed = int(report.speed * gps.MPS_TO_MPH) strspeed = str(speed) currentspeed = 'Current Speed Is: ' + strspeed + ' MPH' msgbox(time + "\n" + currentspeed, "SPEEDO by Jono") except KeyError: pass except KeyboardInterrupt: quit() except StopIteration: session = None print "GPSD has terminated"
(python) Formatting output into variable & Optimisation of a poorly written script
I modified the following script to my needs (original found at Fully parsable dictionary/thesaurus and written by samplebias [at samplebias, very useful, thank you :)]): import textwrap from nltk.corpus import wordnet as wn POS = { 'v': 'verb', 'a': 'adjective', 's': 'satellite adjective', 'n': 'noun', 'r': 'adverb'} def info(word, pos=None): for i, syn in enumerate(wn.synsets(word, pos)): syns = [n.replace('_', ' ') for n in syn.lemma_names] ants = [a for m in syn.lemmas for a in m.antonyms()] ind = ' '*12 defn= textwrap.wrap(syn.definition, 64) print 'sense %d (%s)' % (i + 1, POS[syn.pos]) n1=str('definition: ' + ('\n' + ind).join(defn)) n2=str(' synonyms:', ', '.join(syns)) if ants: n3=str(' antonyms:', ', '.join(a.name for a in ants)) if syn.examples: n4=str(' examples: ' + ('\n' + ind).join(syn.examples)) try: resp = ("From dictionary:\n%s\n%s\n%s\n%s") %(n1, n2, n3, n4) except: try: resp = ("From dictionary:\n%s\n%s\n%s") %(n1, n2, n3) except: try: resp = ("From dictionary:\n%s\n%s") %(n1, n2) except: resp = ("Data not available...") print return resp However, I can tell that I have not modified it very well as it is just wrapped in try/except blocks. But I can't for the life of me think of a better way to do it (still learning python in an abstract manner). I need it formatted into a variable containing \n as a separator for each line as it is written to a file. Any ideas how I can do this better, and without the lists thing that seems to be happening? --Define Sunrise From dictionary: definition: the first light of day (' synonyms:', 'dawn, dawning, morning, aurora, first light, daybreak, break of day, break of the day, dayspring, sunrise, sunup, cockcrow') (' antonyms:', 'sunset') examples: we got up before dawn they talked until morning thanks! :)
Instead of creating a string for each line, just append your text to the output variable from the start. resp = 'From dictionary:\ndefinition: ' + ('\n' + ind).join(defn) +'\n' resp += ' synonyms:' + ', '.join(syns) +'\n' if ants: resp += ' antonyms:' + ', '.join(a.name for a in ants)) +'\n' if syn.examples: resp += ' examples: ' + ('\n' + ind).join(syn.examples)) +'\n'