Convert Python Strings into Json - python

I'm trying to write a program that allows a user to input Questions and Answer for a multi-choice quiz. The questions and answers need to be written to a file in json format.
So far I have code that will ask the user for a Question, the correct answer to the question, then 3 incorrect answers, and write all the strings to a file. But I don't know how to convert the strings to json so they can be used in the Quiz.
The Code I have so far is:
def addToList(filename, data):
question = input('Add Question: ') # prompt user to type what to add
correct = input('Add Correct Answer: ')
wrong1 = input('Add 1st Incorrect Answer: ')
wrong2 = input('Add 2nd Incorrect Answer: ')
wrong3 = input('Add 3rd Incorrect Answer: ')
question = question + '\n' # add a line break to the end
correct = 'correct: ' + correct
wrong1 = 'wrong1: ' + wrong1
wrong2 = 'wrong2: ' + wrong2
wrong3 = 'wrong3: ' + wrong3
data.append(question) # append the question
data.append(correct)
data.append(wrong1)
data.append(wrong2)
data.append(wrong3)
f = open(filename, 'a') # open the file in append mode
f.write(question) # add the new item to the end of the file
f.write(correct)
f.write(wrong1)
f.write(wrong2)
f.write(wrong3)
f.close()
Sorry, I know this is a newbie problem but I'm totally lost here and can't find any examples of user input being put into Json.

First you build a dictionary, then convert it to JSON.
Like this:
import json
# (...)
correct = 'correct: ' + correct
wrong1 = 'wrong1: ' + wrong1
wrong2 = 'wrong2: ' + wrong2
wrong3 = 'wrong3: ' + wrong3
dic = {'correct': correct, 'wrong1': wrong1, 'wrong2': wrong2, 'wrong3': wrong3}
json_str = json.dumps(dic)

Related

How to check if an element is not in file?

How to check if an element is not in a python File, I tried:
if not element in File.read()
But the "not in" doesn't seems to work I also tried:
if element not in File.read()
Edit: Code Snippet
phone = input('Enter a new number :')
imp = phone
if phone not in phbook.read() and phone_rule.match(imp):
phbook = open('Phonebook','a')
phbook.write('Name: ' + firstname + '\n')
phbook.write('Phone: ' + phone + '\n')
if phone in phbook.read():
print('sorry the user already have this phonenumber ')
else:
if phone_rule.match(imp):
phbook = open('Phonebook','a')
phbook.write('Name: ' + firstname + '\n')
phbook.write('phone: ' + phone + '\n')
print('user added !')
else:
print('This is not a good format')
Not working either
You need to open the file before accessing it.
After reading it, the file cursor is at the end of the file.
You could use phbook.seek(0) to set the cursor at the beginning of the file.
A cleaner way would be to ensure you are using your file only once giving it a better structure, eg:
phone = input('Enter a new number :')
imp = phone
phonebook_filename = 'phonebook.txt'
def ensure_phone_in_phonebook(phone):
with open(phonebook_filename) as phbook:
if phone not in phbook.read() and phone_rule.match(imp):
add_data(firstname, phone)
def add_data(firstname, phone):
with open(phonebook_filename, 'a') as phbook:
phbook.write('Name: ' + firstname + '\n')
phbook.write('Phone: ' + phone + '\n')
ensure_phone_in_phonebook(phone)
Also note the usage of context manager statement with.
It bewares you of closing the file after using.
Further informations

What is the correct syntax for this operation?

Writing a game and no matter what I try it keeps giving me a syntax error for the 'as'.
I have tried looking through StackOverflow / changing my code to find a workaround but I have been unable to fix it so far
winner = input("Winner test username")
winnerscore = input("Test score")
open("leaderboardtest.txt","a") as leaderboard
leaderboard.write = "/n" , winner , " : " , winnerscore
(winner and winnerscore variables would have been made earlier just wrote it here during testing)
Invalid syntax highlight on the 'as'.
(I know this is a comparatively simple problem to other things on StackOverflow but I would appreciate any support.)
Looks like you have used incorrect syntax for writing text into file.
f = open("leaderboardtest.txt","a") # open file for append operation
f.write('\n' + winner + ' : ' + winnerscore) # write data whatever you want
f.close() # close file
There you go.
winner = input("Winner test username")
winnerscore = input("Test score")
with open("leaderboardtest.txt","a") as leaderboard:
string_to_write = "\n" + winner + " : " + winnerscore
leaderboard.write(string_to_write)

Python output file formatting - text

This is my first post so please be gentle, im trying to write two text files generated from some user input, the file "hostname - VLAN_config" is fine, i use that file elsewhere in my code, what i do need however is another file (in this case "hostname - Trunk_config" to be formatted in a certain manner in order to use it for another part of my code.
The below code produces a file that looks like this;
", 1, 2, 3"
but i need it to generate a text file that looks like;
1, 2, 3
print ('VLANS')
print('-----------------------------------------------')
print(' ')
condition = True
while (condition == True):
vlan = raw_input('Specify a VLAN id: ')
name = raw_input('What name for this VLAN: ')
print(' ')
with open(hostname + ' - VLAN_config', "ab") as f:
f.write('vlan ' + vlan)
f.write('\n')
f.write('name ' + name)
f.write('\n')
with open(hostname + ' - Trunk_config', "ab") as f:
f.write(', ' + vlan)
test = raw_input('Would you like to add another? [Y] ')
if test == (''):
condition = True
elif test == ('n'):
condition = False
else:
test = raw_input('Invalid input, more?')
if test == ('y'):
condition = True
elif test == ('n'):
condition = False
any help will be much appreciated!
So the only problem is the first comma? Why don't you add a test to check if you are writing the first value?
Other solution: write ', ' only after the user said they want to add another input.

How would I print the fav_genre field for a specific user

So the code below saves the variables username pass etc into a text file with the colons to separate each field. say I wanted to print out the favourite genre of a particular user, how would that be possible as my attempts so far to do so have failed. this is all in python btw. ive edited to add my attempt but its not woking.Any ideas??
usrFile_write = open(textfile, 'a')
usrFile_write.write(username + ' : ' + password + ' : ' + name + ' : ' + dob + ' : ' + fav_artist + ' : ' + fav_genre + ' : ' + '\n')
print('New Account Created!')
print()
usrFile_write.close()
Menu()
my attempt:
textfile = 'user_DB.txt'
username = 'dj'
def getUsersFavouriteGenre():
with open(textfile, 'r') as textIn:
for line in textIn:
information = line.split(' : ')
if information[0] == username:
return information[5]
return 'Failed to find user.'
getUsersFavouriteGenre()
Your code looks good. I'm assuming the issue is your program doesn't output anything, in which case the only issue I see is change your last line getUsersFavouriteGenre() to print(getUsersFavouriteGenre())
If you are getting a specific error or undesired output then you can let us know and we can help you more specifically.

Reading two consecutive lines in Python if one starts with a specific string

I am currently trying to learn Python. I know some basics and I'm trying to practise by making a game. My code so far is:
import time
import datetime
now = datetime.datetime.now()
name = input('What is your name? >> ')
file = open("users.txt","+w")
file.write(name + ' started playing at: ' + now.strftime("%Y-%m-%d %H:%M") + '. \n')
file.close()
account = input('Do you have an account ' + name + '? >> ')
while(account != 'yes'):
if(account == 'no'):
break
account = input('Sorry, I did not understand. Please input yes/no >> ')
if(account == 'yes'):
login = input('Login >>')
passwd = input('Password >>')
if login in open('accounts.txt').read():
if passwd in open('accounts.txt').read():
print('Login Successful ' + login + '!')
else:
print('Password incorrect! The password you typed in is ' + passwd + '.')
else:
print('Login incorrect! The login you typed in is ' + login + '.')
As you probably noticed I am working on a login system. Now please ignore all the bugs and inefficient code etc. I want to focus on how I can get Python to check for a line in a .txt file and, if it's there, check the one below.
My .txt file is:
loggn
pass
__________
I want to make the program multi-account. This is why I am using a .txt file. If you need me to clarify anything, please ask. Thankyou! :)
with open('filename') as f:
for line in f:
if line.startswith('something'):
firstline = line.strip() # strip() removes whitespace surrounding the line
secondline = next(f).strip() # f is an iterator, you can call the next object with next.
Store the results of "open('accounts.txt').read()" yourself, and iterate over them as an array - if you know what line number you are on, it is trivial to check the next. Assuming that every even numbered line is a login, and every odd numbered line is a password, you would have something like this:
success = False
# Storing the value in a variable keeps from reading the file twice
lines = open('account.txt').readlines()
# This removes the newlines at the end of each line
lines = [line.strip() for line in lines]
# Iterate through the number of lines
for idx in range(0, len(lines)):
# Skip password lines
if idx % 2 != 0:
continue
# Check login
if lines[idx] == login:
# Check password
if lines[idx + 1] == password:
success = True
break
if success:
print('Login success!')
else:
print('Login failure')
You may also consider changing your file format: using something that won't occur in the login name (such as a colon, unprintable ASCII character, tab, or similar) followed by the password for each line means you could use your original approach by just checking for (login + "\t" + password) for each line, rather than having to worry about having two lines.

Categories