I'm coding a program for Hypixel SkyBlock Minecraft that tells me the price of items that can be sold for a higher price.
The program is done but I'm running into a issue. I have made a config.json file and it contains information like discord webhook, lowest price, and to notify the user if a item is found. I'm having problems with the lowest price function, basically when I set the lowest price to 1 in the config, the program doesn't work and gets a traceback.
The traceback doesn't matter because I know the issue. When I put the number into config it doesn't work but when i set lowestprice = 1 in program manually it works like when I put the number into config the program thinks maybe the number is a text or something. Here's the config code
with open("config.json", "r") as f:
data = json.load(f)
webhookread = data["webhook"]
notifyread = data["notify"]
lowestpriceread = data["lowestbin"]
WEBHOOK = webhookread
LOWEST_PRICE = lowestpriceread - THE ISSUE
NOTIFY = notifyread
Is there a way I could make the config file put the number as a real number not a text or any of that, so I can still use the config for numbers?
Are the numbers in the json file stored as strings or as numbers? if the json looks like this:
{
"lowestbin" : "123.45"
}
then the price is saved as string and will need to cast to a float type. This is simple to do:
lowestpriceread = float(data["lowestbin"])
Note: this code will thrown an exception if the data in the json cannot be converted into a float.
Related
I am trying to read a file that has a list of tasks. The usernames are displayed on index position 0 on every line of the file. Opening the file, reading the lines and extracting that data I can do. I can get to the point of indexing the data and printing it. What I can't do is create a code to count how many times that user is present in the file. For example if a user is displayed 7 times they must have 7 tasks to complete.
The code I have so far is:
user_global = []
def disp_stats():
with open ("tasks.txt", "r", encoding='cp1252') as tu:
for lines in tu:
data_list = lines.strip("\n").split(", ")
data_list = data_list[0] #this is the data I need to count for how many tasks a user has
user_global.append(data_list)
print(user_global)
My output for this when I print is not what is as expected. What I wanted to achieve is maybe use something like Counter to count how many times a name appears in a global list. That also didn't work out too well.
i have a script which takes and records payments. I have created a .txt file to hold transaction information and the code looks like:
payment_file = open('Payments.txt', 'w')
payment_file.write('Card no: {} | Amount: £{}\n'.format('XXXX-XXXX-XXXX-' + card_number[-4:], "{:,.2f}".format(amount)))
payment_file.close()
As an example when i open the txt it will appear as
Card no: XXXX-XXXX-XXXX-1234 | Amount: £15.00
However once one payment is finished the script loops back to the start allowing for another payment to be made but once the next payment is made and you open the .txt the old payment just gets replaced by the most recent one, how would you make sure the payments just get appended underneath eachother
You need to change this :
payment_file = open('Payments.txt', 'a') # ----------> Here a means appending and not overwriting the existing content.
payment_file.write('Card no: {} | Amount: £{}\n'.format('XXXX-XXXX-XXXX-' + card_number[-4:], "{:,.2f}".format(amount)))
payment_file.close()
You need to use append. Append adds data to the end of files. Write writes over the whole file. Please see the following Python documentation for reading and writing to files: https://docs.python.org/2/tutorial/inputoutput.html#reading-and-writing-files
I am very new to programing and trying to learn by doing creating a text adventure game and reading Python documentation/blogs.
My issue is I'm attempting to save/load data in a text game to create some elements which carry over from game to game and are passed as arguments. Specifically with this example my goal recall, update and load an incrementing iteration each time the game is played past the intro. Specially my intention here is to import the saved march_iteration number, display it to the user as a default name suggestion, then iterate the iteration number and save the updated saved march_iteration number.
From my attempts at debugging this I seem to be updating the value and saving the updated value of 2 to the game.sav file correctly, so I believe my issues is either I'm failing to load the data properly or overwriting the saved value with the static one somehow. I've read as much documentation as I can find but from the articles I've read on saving and loading to json I cannot identify where my code is wrong.
Below is a small code snippet I wrote just to try and get the save/load working. Any insight would be greatly appreciated.
import json
def _save(dummy):
f = open("game.sav", 'w+')
json.dump(world_states, f)
f.close
def _continue(dummy):
f = open("game.sav", 'r+')
world_states = json.load(f)
f.close
world_states = {
"march_iteration" : 1
}
def _resume():
_continue("")
_resume()
print ("world_states['march_iteration']", world_states['march_iteration'])
current_iteration = world_states["march_iteration"]
def name_the_march(curent_iteration=world_states["march_iteration"]):
march_name = input("\nWhat is the name of your march? We suggest TrinMar#{}. >".format(current_iteration))
if len(march_name) == 0:
print("\nThe undifferentiated units shift nerviously, unnerved and confused, perhaps even angry.")
print("\nPlease give us a proper name executor. The march must not be nameless, that would be chaos.")
name_the_march()
else:
print("\nThank you Executor. The {} march begins its long journey.".format(march_name))
world_states['march_iteration'] = (world_states['march_iteration'] +1)
print ("world_states['march_iteration']", world_states['march_iteration'])
#Line above used only for debugging purposed
_save("")
name_the_march()
I seem to have found a solution which works for my purposes allowing me to load, update and resave. It isn't the most efficient but it works, the prints are just there to display the number being properly loaded and updated before being resaved.
Pre-requisite: This example assumes you've already created a file for this to open.
import json
#Initial data
iteration = 1
#Restore from previously saved from a file
with open('filelocation/filename.json') as f:
iteration = json.load(f)
print(iteration)
iteration = iteration + 1
print(iteration)
#save updated data
f = open("filename.json", 'w')
json.dump(iteration, f)
f.close
I'm trying to take two things out of text files that are in folders and output them into a neat list in a single text file. I've never done something like this before and all of the online resources are either too simple for my task or too complex for my task.I have a feeling this task is specific to what I'm trying to do.
[Info]
name = "bridget"
displayname = "BRIDGET"
versiondate = 04,13,2002
mugenversion = 04,14,2001
author = "[fraya]"
pal.defaults = 1
All I'm trying to do is take the "displayname" and "author" text fields and output them to a file in a list with the format "(displayname) by (author)"
a parser was the first thing that came to my mind when I wanted to try this (and python I heard was a good choice for this).
So if anyone could point me in the right direction or give me some building blocks that would be helpful.
You don't need to write a parser; this is (almost) standard .ini file format, which can be read by the configparser module. You'll just need to strip the quotes when you output the values.
To get you started:
import configparser
c = configparser.ConfigParser()
c.read(['myfilename.ini'])
info = c['Info']
displayname = info['displayname'].strip('"')
author = info['author'].strip('"')
print("{} by {}".format(displayname, author))
I'm trying to loop through some JSON data to export to CSV and all is going well until I get to a portion of the data that I need to get certain field values where these fields do not always exist beneath "tags".
I'm getting the error of:
for alarm in tag["alarmst"]:
KeyError: 'alarmst'
I believe from Built-in Exceptions reading that this means the key/field just does not exist.
I read in Errors and Exceptions that I can put this logic in a try statement to say, if this key does not exist, don't give me the error and do something else or move onto the next set of records beneath "tag" where "alarmst" is and just dump that (and the other fields specified) to the file.
I'm having trouble figuring out how to tell this logic to stop giving me this error and to only use the csv_file.writerow() function with all the field values if only the "alarmst" exist.
Since I will be working with one file and processes before this Python process runs will get the "devs" and the "tags" to their own CSV files, I cannot parse the data and cut down on the for loops within the other for loops.
I'm not sure if the issue with the if tag["alarmst"] in tag: is due to there being so many for loops within others, or if I need to use a try statement somehow instead, or if I'm just not doing something else correctly since I'm new to Python at this level of coding but it seems to work for the need thus far.
I'm running this on Windows 10 OS if that makes any difference but I assume it doesn't.
Starting Code:
import json
import csv
with open('C:\\folder\\dev\\TagAlarms.txt',"r") as file:
data = json.load(file)
with open('C:\\folder\\dev\\TagAlarms.csv',"w",newline='') as file:
csv_file = csv.writer(file)
for dev in data["devs"]:
for tag in dev["tags"]:
for alarm in tag["alarmst"]:
csv_file.writerow(alarm['dateStatus'],[alarm['dateStart'], alarm['status'], alarm['type']])
If Code:
import json
import csv
with open('C:\\folder\\dev\\TagAlarms.txt',"r") as file:
data = json.load(file)
with open('C:\\folder\\dev\\TagAlarms.csv',"w",newline='') as file:
csv_file = csv.writer(file)
for dev in data["devs"]:
for tag in dev["tags"]:
for alarm in tag["alarmst"]:
if tag["alarmst"] in tag:
csv_file.writerow(alarm['dateStatus'],[alarm['dateStart'], alarm['status'], alarm['type']])
tag["alarmst"] is what throws the error. It means getting the value from tag associated with the key "alarmst" and there is no such key so it fails. if tag["alarmst"] in tag will throw the same error, and moreover you won't even reach that point if it's below for alarm in tag["alarmst"]:. What you want is:
if "alarmst" in tag:
for alarm in tag["alarmst"]:
But much nicer is:
for alarm in tag.get("alarmst", []):
get is similar to usual square bracket access but the second argument is a default if the key is not found. So if "alarmst" is not in the dictionary this will essentially be:
for alarm in []:
which is just an empty loop that won't run at all.