While loops exits unexpectedly in script - python

Just started learning Python about two months ago, on and off. Still a beginner, but I come from a solid C background. I might not do things the "Python" way, as C is so heavily ingrained into me, but I got my script working. However, I just added a while loop so that I can run it multiple times and exit on user request. The while loop just exits no matter what the input, though. Pretty sure I have my indentation correct. Here's the whole script (with my API key removed). It's the very outside loop, the while finished == 0:
#!/usr/bin/env python3
import sys
import requests
import json
import time
appid = {'key': 'xxxxxxxxxxxxxxx'}
kingston = {'city': "/Canada/Kingston.json", 'city_str': "Kingston, Ontario"}
ottawa = {'city': "/Canada/Ottawa.json", 'city_str': "Ottawa, Ontario"}
toronto = {'city': "/Canada/Toronto.json", 'city_str': "Toronto, Ontario"}
vancouver = {'city': "/Canada/Vancouver.json", 'city_str': "Vancouver, British Columbia"}
sydney = {'city': "/Australia/Sydney.json", 'city_str': "Sydney, Australia"}
wellington = {'city': "/zmw:00000.1.93436.json", 'city_str': "Wellington, New Zealand"}
london = {'city': "/zmw:00000.1.03772.json", 'city_str': "London, UK"}
bergen = {'city': "/zmw:00000.1.01317.json", 'city_str': "Bergen, Norway"}
def cityquery(query):
searchresult = requests.get("http://autocomplete.wunderground.com/aq", params={'query': query})
results = json.loads(searchresult.text)
for index, x in enumerate(results['RESULTS'], start=1):
print(index, x['name'])
selection = input("Please select a number from the list:")
return {'city': results['RESULTS'][int(selection) - 1]['l'] + ".json", 'city_str': results['RESULTS'][int(selection) - 1]['name']}
def getWeather():
finished = 0
while finished == 0:
selected = 0
print("Please choose a city, or enter s to search by city name:")
print("\t1)", toronto['city_str'])
print("\t2)", sydney['city_str'])
print("\t3)", london['city_str'])
print("\t4)", vancouver['city_str'])
print("\t5)", ottawa['city_str'])
print("\t6)", kingston['city_str'])
print("\t7)", wellington['city_str'])
print("\t8)", bergen['city_str'])
while selected == 0:
citynumber = input("Enter a city number or s: ")
if citynumber == '1':
current_city = toronto
selected = 1
elif citynumber == '2':
current_city = sydney
selected = 1
elif citynumber == '3':
current_city = london
selected = 1
elif citynumber == '4':
current_city = vancouver
selected = 1
elif citynumber == '5':
current_city = ottawa
selected = 1
elif citynumber == '6':
current_city = kingston
selected = 1
elif citynumber == '7':
current_city = wellington
selected = 1
elif citynumber == '8':
current_city = bergen
selected = 1
elif citynumber == 's':
searchterm = input("Please type the first few characters of a city name: ")
current_city = cityquery(searchterm)
selected = 1
else:
print("Invalid entry!")
current_time = time.localtime()
print("The current time is", str('{:02d}'.format(current_time[3])) + ":" + str('{:02d}'.format(current_time[4])) + ":" + str('{:02d}'.format(current_time[5])))
print("Forecast for", current_city['city_str'])
#Current conditions
print("Getting current conditions...")
page = requests.get("http://api.wunderground.com/api/" + str(appid['key']) + "/conditions/q/" + current_city['city'])
values = json.loads(page.text)
# DEBUG print(page.text)
# DEBUG print(current_city)
temp = float(values['current_observation']['temp_c'])
if values['current_observation']['windchill_c'] == 'NA':
temp_wc = temp
else:
temp_wc = float(values['current_observation']['windchill_c'])
print("The temperature in", current_city['city_str'], "is currently", str('{:.2f}'.format(temp)) + "C feeling like", str('{:.2f}'.format(temp_wc)) + "C")
pressure_in = float(values['current_observation']['pressure_in'])
pressure_kp = float(values['current_observation']['pressure_mb']) / 10.0
print("The barometric pressure is", str('{:.2f}'.format(pressure_in)), "inches of mercury or", str('{:.1f}'.format(pressure_kp)), "kilopascals.")
wind_speed = float(values['current_observation']['wind_kph'])
wind_gust = float(values['current_observation']['wind_gust_kph'])
wind_dir = str(values['current_observation']['wind_dir'])
if wind_gust == 0:
print("The wind is", str('{:.2f}'.format(wind_speed)), "km/h from the", wind_dir)
else:
print("The wind is", str('{:.2f}'.format(wind_speed)), "km/h, gusting to", str('{:.2f}'.format(wind_gust)), "km/h from the", wind_dir)
#Forecast
print("Getting forecast...")
page = requests.get("http://api.wunderground.com/api/" + str(appid['key']) + "/forecast/q" + current_city['city'])
values = json.loads(page.text)
for x in [0, 1, 2, 3, 4, 5]:
print("Forecast for", values['forecast']['txt_forecast']['forecastday'][x]['title'], ":", values['forecast']['txt_forecast']['forecastday'][x]['fcttext_metric'])
waiting = 0 # loop until valid input
while waiting == 0:
exit = input("Press x to exit or c to check again...")
if exit == 'x' or 'X':
finished = 1
waiting = 1
elif exit == 'c' or 'C':
finished = 0
waiting = 1
else:
finished = 0
waiting = 0
if __name__ == "__main__":
getWeather()

There is an error in line 110 (if elif block inside while waiting). Correct statement would be:
if exit == 'x' or exit == 'X'
your statement reads if exit == 'x' or 'X' which is incorrect. It is comparing exit to x but not to X. What you want to write is if exit is equal to x or exit is equal to X but you have coded for either exit is equal to x or X is True. Now 'X' is always true and it is independent of your input (because you are not comparing it to any variable) and hence the loop exits irrespective of input. Same mistake is there in elif and else block.
This is very much like C

Related

Having Trouble With: Tuple and Int?

So I am making a camel game and I get a weird error that says
"TypeError: '>' not supported between instances of 'tuple' and 'int'"
and I am not sure what this means, I have posted before and I will state this again I am a beginner coder. Thank you to whoever helps here is the code and I will put a comment where the error is that you!
import random
done = False
milesTraveled = 0
thirst = 0
camelTired = 0
nativesDis = -20
canteens = 5
print('''
Welcome to Camel!
You have stolen a camel to make your way across the great Mobi desert.
The natives want their camel back and are chasing you down! Survive your
desert trek and outrun the natives. ''')
while not done:
oasis = (1,21)
if oasis == 4:
print("You found an oasis!")
canteens = 5
thrist = 0
if thirst > 6:
print("You died of thrist!")
spc = input("")
done = True
if thirst > 4:
print("You are thirsty")
#under here
if camelTired > 8:
print("Your camel DIED!")
spc = input("")
done = True
if camelTired > 5:
print("Your camel is getting tired")
if nativesDis == milesTraveled + 20:
print('The natives caught up with you!')
spc=input("")
done = True
if milesTraveled == 200:
print('You Win!')
spc = input("")
done = True
print('''
A. Drink from your canteen.
B. Ahead full speed.
C. Stop and rest.
D. Status check.
Q. Quit ''')
user_choice = input("")
if user_choice.upper() == 'Q':
done = True
elif user_choice.upper() == 'D':
print('''
Miles Traveled: 0
Drinks In Canteen:''',canteens,'''
Thirstyness:''',thirst,'''
The Natives Are 20 Miles Behind You''')
elif user_choice.upper() == 'C':
camelTired = 0
nativesDis = random.randint(7,15)
elif user_choice.upper() == 'B':
milesTraveled = random.randint(10,22)
print("You traveled",milesTraveled,"miles!")
thirst + 1
camelTired = (1,3)
nativesDis = (7,14)
elif user_choice.upper() == 'A':
if canteens > 0:
canteens = canteens - 1
thirst
= 0
You need to take the number out of the tuple and into a variable that is also an integer.
There are multiple integers in your tuple.
You can access them in the following way:
some_tuple_of_integers = (12, 432, 345)
index_zero_integer = some_tuple_of_integers[0]
index_one_integer = some_tuple_of_integers[1]
index_two_integer = some_tuple_of_integers[2]
print(index_zero_integer)
print(index_one_integer)
print(index_two_integer)
Or just straight from the tuple itself without creating a new variable (This can sometimes get unreadable when working with lots of indexes and tuples).
print(some_tuple_of_integers[0])
print(some_tuple_of_integers[1])
print(some_tuple_of_integers[2])
You can then easily compare between other values.
If, for example you have a string from the tuple that you need to compare with another integer, you can change it by doing:
index_two_integer = int(index_two_integer)

Mastermind Python coding

Ok I have a feeling that this is a simple simple issue but I have been staring at this code for about 10 hours now.
The issue I am having is in mastermind is that once I get it to recognize that I have the correct colors in the right spot I can get it to display the right spots with X and the wrong spots with O. I need to be able to convert that so instead of X and O I need it to tell the user that he/she has 2 blacks and one white
For example: The secret code is RGYB The user enters RGOY so then Python relays "You have 2 blacks(The R and G spots) and one 1 White (The Y because it's the right color just in the wrong index) As of right now I got it to display X for the right color in the right spot and anything else it is an O
I will post what I have been working with now but today I am at my wit's end
https://pastebin.com/HKK0T7bQ
if correctColor != "XXXX":
for i in range(4):
if guess[i] == tempCode[i]:
correctColor += "X"
if guess[i] != tempCode[i] in tempCode:
correctColor += "O"
print (correctColor + "\n")
if correctColor == "XXXX":
if attempts == 1:
print ("You think you are sweet because you got it right on the first try? Play me again!")
else:
print ("Well done... You needed " + str(attempts) + " attempts to guess.")
game = False
A few comments
X and O
you use X and 0 to denote the success, it will be easier and faster to use a list or tuple or booleans for this, that way you can use sum() to count how many colors and locations were correct. Then whether you represent that with X and O or red and white pins is a matter for later
compartmentalization
Your game logic (guess input, input validation, do you want to continue, etc) is mixed with the comparison logic, so it would be best to separate the different functions of your program into different methods.
This is an fineexample to introduce object oriented programming, but is so simple it doesn't need OO, but it can help. What you need is a method which takes a series of colours and compares it to another series of colours
Standard library
Python has a very extended standard library, so a lot of stuff you want to do probably already exists
Correct colours
to count the number of letters which occur in 2 strings, you can use collections.Counter
guess = "RGOY "
solution = "RGYB"
a = collections.Counter(guess)
b = collections.Counter(solution)
a & b
Counter({'G': 1, 'R': 1, 'Y': 1})
correct_colours = sum((a & b).values())
3
So the user guessed 3 colours correctly
Correct locations
can be solved with an easy list comprehension
[g == s for g, s in zip(guess, solution)]
[True, True, False, False]
sum(g == s for g, s in zip(guess, solution))
2
so the used put 2 colours on the correct location
This is a MasterMind I made in Python. Hope you like it and it helped you! :)
import random
import time
from tkinter import *
def select_level():
global level
level = level_selector.get()
root.destroy()
root = Tk()
level_selector = Scale(root, from_=1, to=3, tickinterval=1)
level_selector.set(0)
level_selector.pack()
Button(root, text="Select a difficulty level", command=select_level).pack()
mainloop()
cpc_1_digit = 0
cpc_2_digit = 0
cpc_3_digit = 0
cpc_4_digit = 0
p_1_digit = 0
p_2_digit = 0
p_3_digit = 0
p_4_digit = 0
correct_correct = 0
correct_wrong = 0
chances = 0
if level == 1:
chances = 15
elif level == 2:
chances = 10
else:
chances = 7
cpc_1_digit = random.randint(0, 9)
while cpc_2_digit == cpc_1_digit or cpc_2_digit == cpc_3_digit or cpc_2_digit ==
cpc_4_digit:
cpc_2_digit = random.randint(0, 9)
while cpc_3_digit == cpc_1_digit or cpc_3_digit == cpc_2_digit or cpc_3_digit ==
cpc_4_digit:
cpc_3_digit = random.randint(0, 9)
while cpc_4_digit == cpc_1_digit or cpc_4_digit == cpc_2_digit or cpc_4_digit ==
cpc_3_digit:
cpc_4_digit = random.randint(0, 9)
while chances > 0:
correct_correct = 0
correct_wrong = 0
answer = input("Enter a four-digit number with different digits (e.g 1476): ")
p_1_digit = int(answer[0])
p_2_digit = int(answer[1])
p_3_digit = int(answer[2])
p_4_digit = int(answer[3])
if p_1_digit == cpc_1_digit:
correct_correct = int(correct_correct) + 1
elif p_1_digit == cpc_2_digit or p_1_digit == cpc_3_digit or p_1_digit ==
cpc_4_digit:
correct_wrong = int(correct_wrong) + 1
else:
pass
if p_2_digit == cpc_2_digit:
correct_correct = correct_correct + 1
elif p_2_digit == cpc_1_digit or p_2_digit == cpc_3_digit or p_2_digit ==
cpc_4_digit:
correct_wrong = int(correct_wrong) + 1
else:
pass
if p_3_digit == cpc_3_digit:
correct_correct = int(correct_correct) + 1
elif p_3_digit == cpc_1_digit or p_3_digit == cpc_2_digit or p_3_digit ==
cpc_4_digit:
correct_wrong = int(correct_wrong) + 1
else:
pass
if p_4_digit == cpc_4_digit:
correct_correct = int(correct_correct) + 1
elif p_4_digit == cpc_1_digit or p_4_digit == cpc_3_digit or p_4_digit ==
cpc_2_digit:
correct_wrong = int(correct_wrong) + 1
else:
pass
print("")
if int(correct_correct) == 4:
print("Congratsulations! You found the computer's number!")
break
elif int(correct_wrong) > 0 or int(correct_correct) >= 1 and int(correct_correct)
< 4:
print("You got " + str(correct_correct) + " correct digit(s) in the correct
place, and " + str(correct_wrong) + " correct digit(s) but in wrong place.")
elif int(correct_correct) == 0 and int(correct_wrong) == 0:
print("You didn't guess any number, try again!")
else:
raise Exception("CheckError: line 69, something went wrong with the
comparings.")
exit()
print("")
chances = chances - 1
if chances == 0:
print("You lost... The secret number was " + str(cpc_1_digit) + str(cpc_2_digit)
+ str(cpc_3_digit) + str(cpc_4_digit) + ". Try again by rerunning the program.")
time.sleep(4)

Python Assistance Searching a List

"""read file and store into database"""
f = open('C:\\Users\\user.name\\Desktop\\tunes.txt','r')
artist=[""]
song=[""]
album=[""]
genre=[""]
index=0
for line in f:
if index==0:
artist.append(line)
index=index+1
elif index==1:
song.append(line)
index=index+1
elif index==2:
album.append(line)
index=index+1
elif index==3:
genre.append(line)
index=index+1
elif index==4:
index=0
while 1:
selection = int(raw_input("Please select the number that corresponds with what you would like to do.\n1.Search\n2.Recommend\n3.Edit\n4.Save\n"))
if selection == 1:
print "You selected Search"
searchselection = int(raw_input("Please select the number that corresponds with what you would like to do.\n1.Display All Songs\n2.Display All Artists\n3.Search By Artist\n4.Display All Genres\n5.Search by Genre\n6.Display All Playlists\n7.Search By Playlist\n"))
if searchselection == 1:
print '[%s]' % ''.join(map(str, song))
elif searchselection == 2:
print '[%s]' % ''.join(map(str, artist))
elif searchselection == 3:
artistsearch = str(raw_input("\nWhat artist are you searching for?\n"))
artist.index(artistsearch)
print value
elif searchselection == 4:
print '[%s]' % ''.join(map(str, genre))
elif searchselection == 5:
print "display"
elif searchselection == 6:
print "display"
elif searchselection == 7:
print "display"
break
elif selection == 2:
print "You selected recommend."
recommendselection = int(raw_input("Please select the number that corresponds with what you would like to do.\n1.Recommend by Song Title\n2.Recommend by Artist Name\n"))
if recommendselection == 1:
songrec = str(raw_input("Please enter the song title\n"))
elif recommendselection == 2:
artistrec = str(raw_input("Please enter the Artist's name\n"))
break
elif selection == 3:
print "You selected edit."
editselection = int(raw_input("Please select the number that corresponds with what you would like to do.\n1.Add a New Song\n2.Create New Playlist\n3.Add a song to a current playlist"))
if editselection == 1:
songadd = str(raw_input("Please enter the EVERYTHING\n"))
elif editselection == 2:
playistcreate = str(raw_input("Please enter the name of the Playlist\n"))
elif editselection == 3:
playlistadd = str(raw_input("Please enter the name of the playlist\n"))
break
elif selection == 4:
print "You selected Save."
f.close()
break
So that is what I have thus far. This is an ongoing python project, and right now I am stumped; I am trying to search by artist like if Justin Timberlake is typed in by the user as "artistsearch" then I want the index to be pulled so that I can match the index in the song list and display that information to the user.
Any help determining why Justin Timberlake is not a value on the list even though the name shows up when I run the display all artists option would be greatly appreciated.
Also being pointed in the right direction for matching list indexes would be great as well. This is an example of the tunes.txt:
Alicia Keys
No One
As I Am
R&B/Soul;Syl tunes
Everything But the Girl
Missing
Amplified Heart
Alternative;Syl tunes
Gathering Field
Lost In America
Lost In America
Rock
Ellie Goulding
Burn
Halcyon
Pop;Road tunes
Justin Timberlake
Mirrors
Mirrors (Radio Edit) - Single
Pop;Syl tunes
I think you should create a specific class for the data you want to store, and then create a list of objects that instantiate such class:
class Song():
"""Class to store the attributes for each song"""
def __init__ (self):
self.artist = ""
self.song = ""
self.album = ""
self.genre = ""
# List to store all the Song objects
songs_list = []
f = open('C:\\Users\\user.name\\Desktop\\tunes.txt','r')
index=0
for line in f:
# Instantiate an empty Song object
s = Song()
if index == 0:
s.artist = line
index=index+1
elif index == 1:
s.song = line
index = index + 1
elif index == 2:
s.album = line
index = index + 1
elif index == 3:
s.genre = line
index = index+1
elif index == 4:
index = 0
songs_list.append(s)

Python making GUI windows

I wrote a program that makes 3 things which user may choose:
def createLeague(): #creates a list with all teams
file = open('league1.txt', 'r')
teams = []
for line in file:
team = line.split()
teams.append(team)
file.close()
return teams
def getTeam(teams): #this function gets a team that user inputs
result = ' '
choice = input('Enter the team: ')
checkforteam = False
for line in teams:
team = line[0]
if choice == team: #check for input team in all lines
result = team
games = line[1]
wins = line[2] #assign all statistics to the variables with
draws = line[3] #appropriate names
loses = line[4]
checkforteam = True
if checkforteam: #if it is True, it will return the team. If False, returns an error message
print(result, games, wins, draws, loses)
else:
print('No such a team')
def getWinner(teams): #returns a leader
winner = ' '
result = 0
loses = 100
for team in teams:
points = int(team[2])*3 + int(team[3])
lose = int(team[4])#counting all points
if points > result: #find a team with maximum points
result = points
winner = team[0]
loses = lose
elif points == result:
if lose < loses:
winner = team[0]
print('Winner: ', winner)
print('Points: ', result)
def updateScore(teams): #update the table
firsteam = input('Home: ')
secondteam = input('Away: ')
goal1 = int(input('Goals scored by home: '))
goal2 = int(input('Goals scored by away: '))
f = open('nhl.txt', 'w')
for team in teams:
komanda = team[0]
matches = int(team[1])
wins = int(team[2])
draws = int(team[3])
loses = int(team[4])
if firsteam == komanda:
if goal1 > goal2:
matches += 1
wins += 1
elif goal1 == goal2:
matches += 1
draws += 1
else:
matches += 1
loses += 1
elif secondteam == komanda:
if goal1 < goal2:
matches += 1
wins += 1
elif goal1 == goal2:
matches += 1
draws += 1
else:
matches += 1
loses += 1
newline = komanda+ ' '+ str(matches) + ' ' +str(wins)+ ' '+ str(draws) + ' '+ str(loses)+ '\n'
f.write(newline)
f.close()
print('Saved')
teams = createLeague()
loop = 1 #variable that makes 'while' working until user wants to close the program
while loop == 1:
print('0. Exit')
print('1. Find a team')
print('2. Get a leader')
print('3. Update the results')
x = input('Choose: ')
if x == '1':
getTeam(teams)
elif x == '2':
getWinner(teams)
elif x == '3':
updateScore(teams)
elif x == '0':
print('Goodbye!')
loop = 0
else:
print('Wrong!')
Now I want that when I choose 1, 2 or 3 in IDLE, there will be a GUI window appeared where the function that called in while loop will work. I am stucked about it. How I can do it? Please, just show an example for one of the function.

Why is this program not writing the final variable string to it's destination text file?

I'm almost there with using some Python code to pull down stock data strings passed to it from SAS to build a text file to read back into SAS, but the final output text file remains at 0 bytes, despite the code running without error and the print statements I have put in the log seeming to display valid output. Here is the code:
import concurrent.futures
import urllib.request
import json
with open("C:\\Python33\\NASDAQ Stock Strings\\NASDAQ_Config_File_1_a.txt", "r") as myurls:
myurls2 = myurls.read().replace('\n', '')
URLS = [myurls2]
print('URLS =', URLS)
# Retrieve a single page and report the url and contents
def load_url(url, timeout):
conn = urllib.request.urlopen(url, timeout=timeout)
return conn.readall()
# We can use a with statement to ensure threads are cleaned up promptly
with concurrent.futures.ThreadPoolExecutor(max_workers=50) as executor:
# Start the load operations and mark each future with its URL
future_to_url = {executor.submit(load_url, url, 60): url for url in URLS}
c = 0
for future in concurrent.futures.as_completed(future_to_url):
url = future_to_url[future]
a = ''
b = ''
c += 1
mylen = (len(myurls2)) - 1
print('String length = %s' % (len(myurls2)))
a = myurls2[mylen:]
print('a=', a)
if a == 'a':
b = 'Ask'
elif a == 'y':
b = 'Dividend Yield'
elif a == 'b':
b = 'Bid'
elif a == 'd':
b = 'Dividend per Share'
elif a == 'b2':
b = 'Ask (Realtime)'
elif a == 'r1':
b = 'Dividend Pay Date'
elif a == 'b3':
b = 'Bid (Realtime)'
elif a == 'q':
b = 'Ex-Dividend Date'
elif a == 'p':
b = 'Previous Close'
elif a == 'o':
b = 'Open'
elif a == 'c1':
b = 'Change'
elif a == 'd1':
b = 'Last Trade Date'
elif a == 'c':
b = 'Change & Percent Change'
elif a == 'd2':
b = 'Trade Date'
elif a == 'c6':
b = 'Change (Realtime)'
elif a == 't1':
b = 'Last Trade Time'
elif a == 'k2':
b = 'Change Percent (Realtime)'
elif a == 'p2':
b = 'Change in Percent'
elif a == 'c8':
b = 'After Hours Change (Realtime)'
elif a == 'm5':
b = 'Change From 200 Day Moving Average'
elif a == 'c3':
b = 'Commission'
elif a == 'm6':
b = 'Percent Change From 200 Day Moving Average'
elif a == 'g':
b = 'Days Low'
elif a == 'm7':
b = 'Change From 50 Day Moving Average'
elif a == 'h':
b = 'Days High'
elif a == 'm8':
b = 'Percent Change From 50 Day Moving Average'
elif a == 'k1':
b = 'Last Trade (Realtime) With Time'
elif a == 'm3':
b = '50 Day Moving Average'
elif a == 'l':
b = 'Last Trade (With Time)'
elif a == 'm4':
b = '200 Day Moving Average'
elif a == 'l1':
b = 'Last Trade (Price Only)'
elif a == 't8':
b = '1 yr Target Price'
elif a == 'w1':
b = 'Days Value Change'
elif a == 'g1':
b = 'Holdings Gain Percent'
elif a == 'w4':
b = 'Days Value Change (Realtime)'
elif a == 'g3':
b = 'Annualized Gain'
elif a == 'p1':
b = 'Price Paid'
elif a == 'g4':
b = 'Holdings Gain'
elif a == 'm':
b = 'Days Range'
elif a == 'g5':
b = 'Holdings Gain Percent (Realtime)'
elif a == 'm2':
b = 'Days Range (Realtime)'
elif a == 'g6':
b = 'Holdings Gain (Realtime)'
elif a == 'k':
b = '52 Week High'
elif a == 'v':
b = 'More Info'
elif a == 'j':
b = '52 week Low'
elif a == 'j1':
b = 'Market Capitalization'
elif a == 'j5':
b = 'Change From 52 Week Low'
elif a == 'j3':
b = 'Market Cap (Realtime)'
elif a == 'k4':
b = 'Change From 52 week High'
elif a == 'f6':
b = 'Float Shares'
elif a == 'j6':
b = 'Percent Change From 52 week Low'
elif a == 'n':
b ='Name'
elif a == 'k5':
b = 'Percent Change From 52 week High'
elif a == 'n4':
b = 'Notes'
elif a == 'w':
b = '52 week Range'
elif a == 's':
b = 'Symbol'
elif a == 's1':
b = 'Shares Owned'
elif a == 'x':
b = 'Stock Exchange'
elif a == 'j2':
b = 'Shares Outstanding'
elif a == 'v':
b = 'Volume'
elif a == 'a5':
b = 'Ask Size'
elif a == 'b6':
b = 'Bid Size'
elif a == 'k3':
b = 'Last Trade Size'
elif a == 't7':
b = 'Ticker Trend'
elif a == 'a2':
b = 'Average Daily Volume'
elif a == 't6':
b = 'Trade Links'
elif a == 'i5':
b = 'Order Book (Realtime)'
elif a == 'l2':
b = 'High Limit'
elif a == 'e':
b = 'Earnings per Share'
elif a == 'l3':
b = 'Low Limit'
elif a == 'e7':
b = 'EPS Estimate Current Year'
elif a == 'v1':
b = 'Holdings Value'
elif a == 'e8':
b = 'EPS Estimate Next Year'
elif a == 'v7':
b = 'Holdings Value (Realtime)'
elif a == 'e9':
b = 'EPS Estimate Next Quarter'
elif a == 's6':
b = 'Revenue'
elif a == 'b4':
b = 'Book Value'
elif a == 'j4':
b = 'EBITDA'
elif a == 'p5':
b = 'Price-Sales'
elif a == 'p6':
b = 'Price-Book'
elif a == 'r':
b = 'P-E Ratio'
elif a == 'r2':
b = 'P-E Ratio (Realtime)'
elif a == 'r5':
b = 'PEG Ratio'
elif a == 'r6':
b = 'Price - EPS Estimate Current Year'
elif a == 'r7':
b = 'Price - EPS Estimate Next Year'
elif a == 's7':
b = 'Short Ratio'
print('b =', b)
print('c =', c)
filename = "%s" % (b)
filepath = "C:\\Python33\\Stock Data\\" + str(filename) + ".txt"
print(filepath)
print("future.result = ", future.result())
try:
data = future.result()
d = open(filepath,"wb")
d.write(data)
d.close
# do json processing here
except Exception as exc:
for e in range(1,11):
if len(data) > 0:
print('Byte length = %d' % (len(data)))
print(e)
print('%r generated an exception: %s' % (url, exc))
print('retrying %r' % (url))
def load_url(url, timeout):
conn = urllib.request.urlopen(url, timeout=timeout)
return conn.readall()
time.sleep(10)
print("press ENTER to exit")
else:
print('%r page is %d bytes' % (url, len(data)))
The various print statement shows the source text file contents being picked up correctly and passed through to the code ok. The line print("future result =", future.result()) shows the following result:
b'31.90\r\n36.66\r\nN/A\r\n3.69\r\n25.52\r\n27.10\r\n525.33\r\n31.81\r\n56.90\r\n38.23\r\n23.86\r\n2.19\r\n66.93\r\n35.74\r\n21.74\r\n2.10\r\n26.08\r\n14.20\r\n26.73\r\n14.92\r\n48.42\r\n12.49\r\n19.31\r\n4.09\r\n3.37\r\n57.78\r\n45.85\r\n3.32\r\n60.02\r\n2.31\r\n18.50\r\n37.74\r\n3.42\r\n12.46\r\n14.03\r\n1.25\r\n15.13\r\n2.53\r\n1.73\r\n56.72\r\n44.98\r\n35.89\r\n1.05\r\n67.50\r\n17.35\r\n50.72\r\n20.72\r\n50.37\r\n6.27\r\n13.23\r\n77.50\r\n27.62\r\n24.49\r\n34.02\r\n24.56\r\n50.59\r\n25.50\r\n21.53\r\n31.33\r\n4.65\r\n4.65\r\n24.00\r\n52.04\r\n2.73\r\n24.78\r\n39.94\r\n20.57\r\n6.84\r\n2.97\r\n1.27\r\n24.08\r\n20.50\r\n7.44\r\n14.49\r\n13.22\r\n37.62\r\n4.39\r\n44.46\r\n44.46\r\n43.80\r\n22.58\r\n22.58\r\n48.92\r\n14.60\r\n50.12\r\n60.75\r\n2.36\r\n35.10\r\n8.47\r\n29.81\r\n53.13\r\n19.57\r\n12.95\r\n16.76\r\n59.70\r\n16.63\r\n4.74\r\n23.44\r\n37.52\r\n10.37\r\n52.81\r\n107.50\r\n6.64\r\n46.15\r\n15.50\r\n14.85\r\n72.06\r\n79.08\r\n14.25\r\n8.90\r\n1.91\r\n5.54\r\n35.43\r\n5.12\r\n177.09\r\n20.30\r\n20.60\r\n18.80\r\n28.30\r\n31.93\r\n31.93\r\n10.24\r\n1.65\r\n10.09\r\n1.83\r\n2.15\r\n74.23\r\n7.51\r\n14.38\r\n123.76\r\n12.89\r\n6.17\r\n23.22\r\n11.80\r\n19.70\r\n9.95\r\n17.93\r\n1.81\r\n4.18\r\n2.13\r\n42.81\r\n44.29\r\nN/A\r\n32.72\r\n373.95\r\n21.12\r\n1.85\r\n114.72\r\n20.25\r\n2.03\r\n16.89\r\n57.65\r\n13.28\r\n16.79\r\n42.24\r\n33.87\r\n77.08\r\n3.49\r\n7.26\r\nN/A\r\n33.95\r\n34.02\r\n32.33\r\n3.07\r\n2.42\r\n16.00\r\n2.87\r\n10.26\r\nN/A\r\nN/A\r\n13.45\r\n9.70\r\n17.36\r\n2.89\r\n14.61\r\n14.61\r\n29.00\r\n20.78\r\n11.39\r\n8.25\r\n71.81\r\n3.34\r\n22.15\r\n80.82\r\n47.80\r\n6.56\r\n26.67\r\n2.17\r\n28.43\r\n5.06\r\n48.16\r\nN/A\r\n6.00\r\n4.29\r\n20.20\r\n22.79\r\n17.75\r\n17.52\r\n17.52\r\n13.80\r\n'
This looks like the correct values to me, but just needing cleaning up. The destination text file resolves correctly and the all OK statement below the error handling returns the byte length of the URL submission correctly. The text file though remains empty.
Can anyone spot an obvious mistake I have made?
Thanks
Move d = open(filepath,"wb") and d.close() outside of the for loop.
Every iteration of the loop deletes and overwrites the file.
http://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files
EDIT:
I didn't see that the filepath is calculated in the forloop. I'd do what #sabbahillel pointed out, and open the file with "ab" mode to ensure it's not overwritten.
The code
d.close
gives the result
>>> d.close
<built-in method close of file object at 0x0000000002C171E0>
Which is a variable description. In order to close the file you need to specify
d.close()
If the various values all apply to the same piece of data, then you would probably be better off building a csv file with the field headers in row 1 showing the header strings that you want then get the data and use a translation dictionary.
indict = {'a':'Ask', 'b':'y', 'd':'Dividend per Share', 'b2':'Ask (Realtime)'}
outname = indict[inval]
Output the csv file using csv.DictWriter() with the field headers that you choose using the appropriate parameters such as restval='' and extrasaction='ignore'
Now you can process the csv file and perform your analysis on all the data using only one input file rather than a separate input file for each piece of data.
Note: if you somehow open the same file twice, open it with 'ab' in order not to wipe out the previous data. It is a better idea to always open with 'ab' instead of 'wb' unless you specifically want to wipe out any previous data.

Categories

Resources