Right now i am working with a file .txt with this information:
["corrector", "Enabled"]
["Inteligencia", "Enabled"]
Then in my python program it loads that data at the very beggining, this way:
for line in open("menu.txt", 'r'):
retrieved = json.loads(line)
if retrieved[0] == "corrector":
corrector = retrieved[1]
if retrieved[0] == "Inteligencia":
Inteligencia = retrieved[1]
So far it works perfect, however as this is for a chat bot, i want to make possible to change the value of that variables directly from the chat, and i tried this code when i call "!Enable corrector" from the chat.
if corrector == "Enabled":
room.message("ERROR: Already Enabled")
else:
data = []
with open('menu.txt', 'r+') as f:
for line in f:
data_line = json.loads(line)
if data_line[0] == "corrector":
data_line[1] = "Enabled"
data.append(data_line)
f.seek(0)
f.writelines(["%s\n" % json.dumps(i) for i in data])
f.truncate()
room.message("corrector enabled")
That also works, and if i open the .txt file i can see the value it's already changed. The real problem is that python didn't seem to accept that i changed a variable, and it still thinks it's "disabled" while it's already "enabled". It won't read the variable as "enabled" until i restart the program.
I was wondering if there is a refresh option for variables or a workaround to change the value of a variables on the fly and make the effect lasts without a restart.
change the value of a variables on the fly
This code changes the value of a variable on the fly:
a = 1
a = 2
Your question suggests that you want to be able to look up a value by a calculated name. The solution is to use a dict:
mydict = {'corrector':0}
mydict['corrector'] = 1
If you want to change the values in the file, you'll need to write out a new file based on the data you have. It looks like you're loading json, so the json module will help you out with that.
Related
hello beautiful people so i have a text file like this :
user = user447
pass = 455555az
type = registred
date = 1 year
and i want to read the file and rewrite it like this
user|pass|type|date,
line by line,
i tried so many ways , i seem stuck since i have to deal with 1 million account
with open(file, "r") as f:
data = []
for line in f:
key = line.rstrip('\n').split('=')
key1 = key[1:2]
You don't need to read the entire file all at once, instead, you can just read it in parts and write as you read (note the with block is used for two open() context managers, though you can nest them inside each other just as easily)
with open(source) as fh_src, open(destination, "w") as fh_dest:
block = []
for lineno, line in enumerate(fh_src, 1):
# .split("=", 1)[-1] captures everything after the first =
# this is also an opportunity to verify the key
block.append(line.split("=", 1)[-1].strip())
if len(block) == 4:
fh_dest.write("{}|{}|{}|{}\n".format(*block))
block = [] # reset block after each write
it's definitely worth creating some safeguards, however!
checking if lines really start with some key if you have a set of known keys or have some you intend to omit, or if you have some dynamic set of keys (say some users have a collection of previous password hashes, or different comments)
checking if block at the end (it should be cleared and write!)
checking = is really in each line or that any comments are kept or discarded
opening "w" will remove destination if it exists already (perhaps from a botched previous run), which may be undesirable
(lineno is only included to simplify discovering bad lines)
So I am trying to add save files to my text-adventure game that can't be edited by the user. This is so that they can't cheat by editing the dictionary inside of it. So far all I've done is a few algorithms that can be easily bypassed if you connected the dots. Basically it's this.
import sys,os,ast
dictionary = {...}
save_dictionary = {...}
def save():
filehandler = open("dictionary.txt", "a")
data = str(dictionary)
filehandler.write(data)
filehandler.close()
def savecode():
savecode = dictionary.values()
total = sum(savecode)
save_dictionary['savecodes'] = round(math formulas)
filehandler = open("save_dictionary.txt", "a")
data = str(save_dictionary)
filehandler.write(data)
filehandler.close()
def load():
with open('dictionary.txt') as f:
data = f.read()
save = ast.literal_eval(data)
f.close()
But the problem I'm facing is that it is easily by-passible if you just add an amount and equally subtract an amount, which would make the sum the same, making everything work the same. I did make it so that anytime the game itself detects any changes it immediately deletes all save files and makes you start over.
So is the solution making the files unable to be accessed at all? Or is it that the python file will detect the time it was created? I have no idea. It could be another option.
You can't hide files from the super user. They bought their computer and they reserve the right to read and edit whatever files they please. And no program will ever have higher permissions than the administrator.
Your best bet is to encrypt the data inside the file. So that if the user tries to edit, the program won't function properly.
A question that might be more relevant:
https://gamedev.stackexchange.com/questions/48629/how-do-i-prevent-memory-modification-cheats
I have a simple program that take input from user and put them into a dict. After then I want to store that data into json file (I searched and found only json useful)
for example
mydict = {}
while True:
user = input("Enter key: ")
if user in mydict.keys(): #if the key already exist only print
print ("{} ---> {}".format(user,mydict[user]))
continue
mn = input("Enter value: ")
app = input ("Apply?: ")
if app == "y":
mydict[user] = mn
with open ("mydict.json","a+") as f:
json.dump(mydict,f)
with open ("mydict.json") as t:
mydict = json.load(t)
Every time user enter a key and value, I want to add them into dict, after then store that dict in json file. And every time I want to read that json file so I can refresh the dict in program.
Those codes above raised ValueError: Extra data: . I understood error occured because I'm adding the dict to json file every time so there are more than one dict. But how can I add whole dict at once? I didn't want to use w mode because I don't want to overwrite the file and I'm new in Json.
Program must be infinite and I have to refresh dict every time, that's why I couldn't find any solution or try anything, since I'm new on Json.
If you want to use JSon, then you will have to use the 'w' option when opening the file for writing. The 'a+' option will append your full dict to the file right after its previously saved version.
Why wouldn't you use csv instead ? With 'a+' option, any newly entered user info will be appended to the end of the file and transforming its content at reading time to a dict is quite easy and should look something like:
import csv
with open('your_dict.json', 'r') as fp:
yourDict = {key: value for key,value in csv.reader(fp, delimiter='\t')
while the saving counterpart would look like:
yourDictWriter = csv.writer( open('your_dict.json','a+'), delimiter='\t') )
#...
yourDictWriter.writerow([key, value])
Another approach would be to use MongoDB, a database designed for storing json documents. Then you won't have to worry about overwriting files, encoding json, and so on, since the database and driver will manage this for you. (Also note that it makes your code more concise.) Assuming you have MongoDB installed and running, you could use it like this:
import pymongo
client = MongoClient()
db = client.test_database.test_collection
while True:
user = input("Enter key: ")
if db.find_one({'user': user}) #if the key already exist only print
print ("{} ---> {}".format(user, db.find_one({'user':user})['value'])
continue
mn = input("Enter value: ")
app = input ("Apply?: ")
if app == "y":
db.insert({'user':user, 'value':value})
With your code as it is right now, you have no reason to append to the file. You're converting the entire dict to JSON and writing it all to file anyway, so it doesn't matter if you lose the previous data. a is no more efficient than w here. In fact it's worse because the file will take much more space on disk.
Using the CSV module as Schmouk said is a good approach, as long as your data has a simple structure. In this case you just have a table with two columns and many rows, so a CSV is appropriate, and also more efficient.
If each row has a more complex structure, such as nested dicts and or lists, or different fields for each row, then JSON will be more useful. You can still append one row at a time. Just write each row into a single line, and have each row be an entire JSON object on its own. Reading files one line at a time is normal and easy in Python.
By the way, there is no need for the last two lines. You only need to read in the JSON when the program starts (as Moses has shown you) so you have access to data from previous runs. After that you can just use the variable mydict and it will remember all the keys you've added to it.
I need a little bit of help on overwriting python variables. Here's the best example I could give. IF someone opens up my program (in .exe or .py) and this were to come up:
var = 5
var = raw_input("Enter the new variable value: ") ##THE PERSON ENTERS 3
var = 3
Now, the user closes the file/program, next time they open it, they want the program to remember that var = 3, so it overwrote the var = 5 with var = 3. I don't know if this is possible, but if it is, could you let me know?
To Clarify: I want my .py or .exe to remember that a variable was changed, and overwrite the old variable with the new one, so the next time they open the file, the variable is already changed.
You'll need to somehow store the value, for example in a file, database, or with some service.
For example, using a simple file:
import io,os
try:
with io.open('~/.jordan_last_value', 'r', encoding='utf-8') as f:
var = f.read()
except IOError: # Read failed
var = raw_input('Enter the new variable value')
# Save value to disk
with io.open('~/.jordan_last_value', 'w', encoding='utf-8') as f:
f.write(var)
print ('Current value is ' + var)
As you can see, this can be somewhat complex, so you may want to refresh your knowledge of file handling. Also, this example code can just store strings.
If you want to be able to store more complex objects, you'll need a way to transform them from and to bytestrings first. Have a look at the json or pickle modules for that.
You can use pickle module, json or whatever :P
Using the pickle module:
import pickle
try: # try to open the file
with open('jordan_data.pkl', 'r+') as f:
var = pickle.load(f)
except IOError: # if it doesn't exist, get new input
var = raw_input("Enter the new variable value: ") # THE PERSON ENTERS 3
with open('jordan_data.pkl', 'a+') as f: # 'a' will create the file if it doesn't exist
pickle.dump(var, f) # then, save the file
I'm writing a small program that helps you keep track of what page you're on in your books. I'm not a fan of bookmarks, so I thought "What if I could create a program that would take user input, and then display the number or string of text that they wrote, which in this case would be the page number they're on, and allow them to change it whenever they need to?" It would only take a few lines of code, but the problem is, how can I get it to display the same number the next time I open the program? The variables would reset, would they not? Is there a way to permanently change a variable in this way?
You can store the values in a file, and then load them at start up.
The code would look somewhat like this
variable1 = "fi" #start the variable, they can come from the main program instead
variable2 = 2
datatowrite = str(variable1) + "\n" + str(variable2) #converts all the variables to string and packs them together broken apart by a new line
f = file("/file.txt",'w')
f.write(datatowrite) #Writes the packed variable to the file
f.close() #Closes the file !IMPORTANT TO DO!
The Code to read the data would be:
import string
f = file("/file.txt",'r') #Opens the file
data = f.read() #reads the file into data
if not len(data) > 4: #Checks if anything is in the file, if not creates the variables (doesn't have to be four)
variable1 = "fi"
variable2 = 2
else:
data = string.split(data,"\n") #Splits up the data in the file with the new line and removes the new line
variable1 = data[0] #the first part of the split
variable2 = int(data[1]) #Converts second part of strip to the type needed
Bear in mind with this method the variable file is stored in plaintext with the application. Any user could edit the variables and change the programs behaviour
You need to store it on disk. Unless you want to be really fancy, you can just use something like CSV, JSON, or YAML to make structured data easier.
Also check out the python pickle module.
Variables have several lifetimes:
If they're inside of a block of code, their value only exists for that block of code. This covers functions, loops, and conditionals.
If they're inside of an object, their value only exists for the life of that object.
If the object is dereferenced, or you leave your code of block early, the value of the variable is lost.
If you want to maintain the value of something in particular, you have to persist it. Persistence allows you to write a variable out to disk (and yes, databases are technically out-to-disk), and retrieve it at a later time - after the lifetime of the variable has expired, or when the program is restarted.
You've got several options for how you want to persist the location of their page - a heavy-handed approach would be to use SQLite; a slightly less heavy handed approach would be to unpickle the object, or simply write to a text file.