I was working on a cryptocurrency and everything else works but this, you can have a mine once, but then you can't after one time because the balance is the same. It should be simple. I need help with the balance and saving it and being able to mine more than once,
You will probly be able to fix this instantly
import os
import time
from anthonys_balance import lbalance
balance = 1
user = input("Username:")
f = open(user + "'s file", "w")
username = user
ubalance = balance
userbalance = f'{balance}{username}'
log = f'{user} has a balance of {lbalance} Coinon'
y=f'{user}s_balance.py'
if os.path.exists(y):
if os.path.isfile(y):
print("file is present")
else:
f = open(user + "s_balance.py", "x")
f.write (f'lbalance = {ubalance}')
f.close()
f = open(user + "'s file", "w")
f.write(str(log))
f.close()
userfile = user + "s_balance.txt"
os.system("clear")
def select():
from anthonys_balance import lbalance
print(f'{user} has a balance of {lbalance} Coinon')
print("Mine = 1")
print("Send = 2")
options = input("Selection:")
if options == "1":
def mine():
x = 1
if x == 1:
time.sleep(3)
#import user + "'s balance.py"
from anthonys_balance import lbalance
lnbalance = lbalance +1
f = open(user + "'s file", "w")
f.write(f'{user} has a balance of {lnbalance +1} Coinons')
f.close()
f = open(f'{user}s_balance.py', "w")
f.write(f'lbalance = {lnbalance +1}')
f.close()
print(f'{user} has a balance of {lnbalance +1} Coinons')
print("mine success")
input("Continue?")
f = open(user + "'s file", "w")
f.write(f'{user} has a balance of {lnbalance +1} Coinons')
f.close()
mine()
mine()
pass
select()
I didn't run it but I see few problems
you have mess in code. To make code more readable you could
put mine() outside select(),
convert some code into function - ie. read_data, save_data, log,
put all functions directly after import
send values to function as arguments
(see more in PEP 8 -- Style Guide for PythonCode)
you use import to load data but import reads file only once and it remember it - so it doesn't load again the same file. Python assumes that code doesn't change and data should be in files like .txt, .json, .ini, .yaml, `pickle, etc. or in database
This is my version with all changes.
I keep balance in dictionary data and I save it in .json - so I can keep other information data and save it in file - ie. username.
I load data only once - at start - and later I uses value which I have in memory and only I save new value in file. If there is no file at start then I create new one with default values.
I use while True to run code many times and user may select X to exit it.
import os
import time
import json
import datetime
# --- functions ---
def log(username, text):
dt = datetime.datetime.now().strftime('%Y.%m.%d %H:%M.%S')
filename = f'{username}.log'
with open(filename, "a") as f: # append
f.write(f'{dt} {text} \n')
def load_data(username):
filename = f'{username}.json'
if os.path.exists(filename) and os.path.isfile(filename):
with open(filename) as f:
data = json.load(f)
else:
data = None
return data
def save_data(username, data):
filename = f'{username}.json'
with open(filename, 'w') as f:
json.dump(data, f)
def select(username, data):
while True:
print(f'{username} has a balance of {data["balance"]} Coinons')
print("1. Mine")
print("2. Send")
print("X. Exit")
answer = input("Selection:")
answer = answer.upper().strip()
if answer == "X":
return
elif answer == "1":
mine(username, data)
elif answer == "2":
print('not created')
#send(username, data)
def mine(username, data):
time.sleep(3)
data['balance'] += 1
save_data(username, data)
log(username, f'{username} has balance {data["balance"]} Coinon')
print(f'{username} has a balance of {data["balance"]} Coinons')
print("mine success")
input("Press any key to continue.")
# --- main ---
username = input("Username: ")
# load data from file or use default value
data = load_data(username)
if not data:
data = {'balance': 1, "username": username}
save_data(username, data)
log(username, f'{username} has balance {data["balance"]} Coinon')
os.system("clear")
select(username, data)
Related
I am looking for some help on a project I am doing where I need to output the responses to the console as well as write them to a file. I am having trouble figuring that part out. I have been able to write the responses to a file successfully, but not both at the same time. Can someone help with that portion? The only lines that need to be written to the file are the ones that I have currently being written to a file
from datetime import datetime
import requests
import pytemperature
def main():
api_start = 'https://api.openweathermap.org/data/2.5/weather?q='
api_key = '&appid=91b8698c2ed6c192aabde7c9e75d23cb'
now = datetime.now()
filename = input("\nEnter the output filename: ")
myfile = None
try:
myfile = open(filename, "w")
except:
print("Unable to open file " + filename +
"\nData will not be saved to a file")
choice = "y"
print("ISQA 3900 Open Weather API", file=myfile)
print(now.strftime("%A, %B %d, %Y"), file=myfile)
while choice.lower() == "y":
# input city and country code
city = input("Enter city: ")
print("Use ISO letter country code like: https://countrycode.org/")
country = input("Enter country code: ")
# app configures url to generate json data
url = api_start + city + ',' + country + api_key
json_data = requests.get(url).json()
try:
# getting weather data from json
weather_description = json_data['weather'][0]['description']
# printing weather information
print("\nThe Weather Report for " + city + " in " + country + " is:", file=myfile)
print("\tCurrent conditions: ", weather_description, file=myfile)
# getting temperature data from json
current_temp_kelvin = json_data['main']['temp']
current_temp_fahrenheit = pytemperature.k2f(current_temp_kelvin)
# printing temperature information
print("\tCurrent temperature in Fahrenheit:", current_temp_fahrenheit, file=myfile)
# getting pressure data from json
current_pressure = json_data['main']['pressure']
# printing pressure information
print("\tCurrent pressure in HPA:", current_pressure, file=myfile)
# getting humidity data from json
current_humidity = json_data['main']['humidity']
# printing humidity information
print("\tCurrent humidity:", "%s%%" % current_humidity, file=myfile)
# getting expected low temp data from json
expected_low_temp = json_data['main']['temp_min']
expected_low_temp = pytemperature.k2f(expected_low_temp)
# printing expected low temp information
print("\tExpected low temperature in Fahrenheit:", expected_low_temp, file=myfile)
# getting expected high temp data from json
expected_high_temp = json_data['main']['temp_max']
expected_high_temp = pytemperature.k2f(expected_high_temp)
# printing expected high temp information
print("\tExpected high temperature in Fahrenheit:", expected_high_temp, file=myfile)
choice = input("Continue (y/n)?: ")
print()
except:
print("Unable to access ", city, " in ", country)
print("Verify city name and country code")
if myfile:
myfile.close()
print('Thank you - Goodbye')
if __name__ == "__main__":
main()
Honestly I am kind of at a loss on this one for some reason it is just kicking my butt.
For printing a single object:
def mprint(text, file):
print(text)
print(text, file = file)
A more general one for printing several objects:
def mprint(*args):
print(*args[:-1])
print(*args[:-1],file = args[-1])
Usage: mprint(obj1, obj2, ... , myfile)
A completely general print function replacement would look something like:
def myprint(*args, file=None, **kwargs):
print(*args, **kwargs) # print to screen
if file is not None:
print(*args, file=fp, **kwargs) # print to file
this will let you use end=.. etc. as well
filename = input("\nEnter the output filename: ")
myfile = None
try:
myfile = open(filename, "w")
except:
print("Unable to open file " + filename +
"\nData will not be saved to a file")
choice = "y"
myprint("ISQA 3900 Open Weather API", file=myfile)
myprint(now.strftime("%A, %B %d, %Y"), file=myfile)
if myfile couldn't be opened and is therefore None, the myprint function will only print to screen.
I am beginner, so I tried solving this problem and I couldn't.I don't know how to explain the problem but I'll try, First you'll have to create 2 python files 1 called setup.py and the other one game.py. Most people will think this is weird but I want you to see what happens when you run the code so you'll understand more.
setup.py
from setuptools import setup
setup(
name ="Game",
version= "0.1",
py_modules=['Game'],
install_requires=[
'Click',
],
entry_points = '''
[console_scripts]
Game=Game:cli
''',
)
game.py
from random import *
from time import *
import click
dt = 5000
userinventroy = ["Phone"]
f = open("wallet.txt","w")
f.write(str(dt))
f.close
#click.group()
def cli():
pass
#cli.command()
def bet():
global dt
global f
guessthenumber = randint(1,2)
if int(input("Guess the number:")) == guessthenumber:
print("Correct you won 250 DT!!")
w = 250
f = open("wallet.txt","r")
old_wallet = f.read()
int(old_wallet)
new_wallet = old_wallet + w
f = open("wallet.txt","w")
f.write(str(new_wallet))
f.close()
else:
print("You lost.")
#cli.command()
def wallet():
global f
f= open("wallet.txt","r")
print("You have :",f.read())
f.close()
After you have these two files created I want you to go to the terminal and type
" pip install --editable . " (without strings).
The main problem now is : so once you start this betting game which is guessing a number from 1 to 5 and if you guess it you get 250 coins or credits but it doesn't store it
if you type game wallet to check the new value it is the same value that i set and this is killing me, Please i would truly appreciate it if you help me, thank you.
Maybe make a file and store the wallet count in there:
f = open('wallet.txt', 'w' )
f.write(str(wallet))
f.close()
Then when they play the game again:
f = open("wallet.txt", "r")
print("Wallet balance: ",f.read())
f.close()
EDIT: If you have multiple users, and want to track their balances - ask them to enter a username then use that username as the file name:
user = input("Enter your name")
filename = user + " .txt"
f = open(filename, "w")
f.write(str(wallet))
f.close()
Now you'll have files for each user, and can also read their file when they put in their username.
EDIT 2: If you are wanting to carry on adding to it do this:
First we want to scrape what's in the user's wallet already, then replace it:
print("You won 250!") #or whatever they won
#reading wallet file
f = open('wallet.txt', 'r')
old_wallet = f.read()
new_wallet = old_wallet + wallet
#writing to wallet file
f = open('wallet.txt', 'w')
f.write(str(new_wallet)) #making sure it's a float what's in the file
f.close()
Final edit: adding to the wallet at the start causes errors as it has already been written to.
The problem was i did set a variable called "dt = 5000" which is the user wallet at the beginning of the code and everytime you win the bet, 250 won't be added since its getting reset everytime you type a command, what i did was i set the variable in the function this solved the main problem now but it will lead to more problems, this is a fix but not an efficient one.
setup.py
from setuptools import setup
setup(
name ="Game",
version= "0.1",
py_modules=['Game'],
install_requires=[
'Click',
],
entry_points = '''
[console_scripts]
Game=Game:cli
''',
)
game.py
from random import *
from time import *
import click
userinventroy = ["Phone"]
#click.group()
def cli():
pass
#cli.command()
def bet():
global dt
global f
guessthenumber = randint(1,2)
dt = 5000
f = open("wallet.txt","w")
f.write(str(dt))
f.close
if int(input("Guess the number:")) == guessthenumber:
print("Correct you won 250 DT!!")
w = 250
f = open("wallet.txt","r")
old_wallet = f.read()
new_wallet = int(old_wallet) + int(w)
f = open("wallet.txt","w")
f.write(str(new_wallet))
f.close()
else:
print("You lost.")
#cli.command()
def wallet():
global dt
global f
f= open("wallet.txt","r")
print("You have :",f.read())
f.close()
After you have these two files created I want you to go to the terminal and type
" pip install --editable . " (without strings).
If I have a list of seven items with similar names, it will only populate six of them in the pickle file. Six seems to be where the issues start, but if I move that up to nine items, it will show eight.
In the code, it does not show them under the full iteration of data2 in function access_passwords. But they will pull accurately under function access_one_pw. So they're populating, but the iteration that should be printing the device + the password does not seem to be working correctly.
def add_passwords():
data = []
newdata = []
pw_file_r = open('K:\\Downloads\\Chrome Downloads\\pickle.txt', 'rb') # modify to local folder and create
# pickle.txt document
while True:
try:
data.append(pickle.load(pw_file_r))
except EOFError:
break
pw_file_r.close()
pwordN = int(input('Enter the number of devices to name: '))
for i in range(pwordN):
raw = input('Enter device name ' + str(i) + ' : ')
newdata.append(raw)
for x in newdata:
global keyvar
data.append(x)
pw_file_w = open('K:\\Downloads\\Chrome Downloads\\pickle.txt', 'ab') # modify to local folder
pickle.dump(x, pw_file_w)
pw_file_r.close()
newpass = getpass.win_getpass(prompt='Enter the password for the device ' + x + ': ', stream=None)
newpass_to_bytes = bytes(newpass, 'utf-8')
key = base64.urlsafe_b64encode(bytes(keyvar, 'utf-8'))
cipher_suite = Fernet(key)
ciphered_text = cipher_suite.encrypt(newpass_to_bytes)
db_update = shelve.open('K:\\Downloads\\Chrome Downloads\\device_shelf.db') # modify to local folder
try:
db_update[x] = ciphered_text
finally:
db_update.close()
def access_passwords():
data2 = []
data2.clear()
global keyvar
pw_file_r = open('K:\\Downloads\\Chrome Downloads\\pickle.txt', 'rb') # modify to local folder
while 1:
try:
data2.append(pickle.load(pw_file_r))
except EOFError:
break
pw_file_r.close()
for x1 in data2:
db_read = shelve.open('K:\\Downloads\\Chrome Downloads\\device_shelf.db') # modify to local folder
try:
device = db_read[x1]
finally:
db_read.close()
key = base64.urlsafe_b64encode(bytes(keyvar, 'utf-8'))
cipher_suite = Fernet(key)
ciphered_text = device
unciphered_text = (cipher_suite.decrypt(ciphered_text))
plaintxt = bytes(unciphered_text).decode("utf-8")
print('The device ' + x1 + ' has a password of ' + plaintxt)
restart = input('Do you want to restart the program? [Yes/No]: ')
if restart == 'Yes':
frun()
else:
pass
Using windows 10
Here's a sample of my code, where the problem is:
if choice2 == "d":
amount = int(raw_input("How much money would you like to deposit? Current balance: %i : " % intBalance))
newBalance = intBalance + amount
print "Current balance: %i" %newBalance
f.close()
os.remove("accounts.txt")
f = open("accounts.txt", "a+")
fileVar.remove(accessedAccount[2])
fileVar.remove(accessedAccount[1])
fileVar.remove(accessedAccount[0])
f.write(accessedAccount[0] + "\n")
f.write(accessedAccount[1] + "\n")
newBalance = str(newBalance)
f.write(newBalance + "\n")
for item in fileVar:
f.write("%s\n" %item)
test = raw_input("Waiting for input")
At the bottom is the code that writes the information of the list (called fileVar) into the text file (called f). It does write the information to the list but it messes up the order of the lines which cannot happen with the program I am making because the file must be able to be read back to the program to work later on.
Here is my entire code for context:
import os
import string
again = "y"
f = open('accounts.txt', 'a+')
fileVar = f.read().splitlines()
print fileVar
accessedAccount = []
data = f.read()
choice = raw_input("What would you like to do? (add/remove a bank account, access a bank account): ")
if choice == "a":
while again == "y":
accName = raw_input("Account owner's name: ")
accType = raw_input("Account type: ")
accBal = "0"
f.seek(0, 2)
f.write(accName + "\n")
f.write(accType + "\n")
f.write(accBal)
f.write("\n")
again = raw_input("Add another account?: ")
if choice == "a2":
account = raw_input("What is the name of the account you wish to access?: ")
for i, line in enumerate(fileVar):
if account in line:
for j in fileVar[i:i+3]:
print j
accessedAccount.append(j)
print accessedAccount
balance = accessedAccount[2]
intBalance = int(balance)
print accessedAccount
choice2 = raw_input("This is your bank account. What would you like to do now? (Withdraw/deposit, exit): ")
if choice2 == "d":
amount = int(raw_input("How much money would you like to deposit? Current balance: %i : " %intBalance))
newBalance = intBalance + amount
print "Current balance: %i" %newBalance
f.close()
os.remove("accounts.txt")
f = open ("accounts.txt", "a+")
fileVar.remove(accessedAccount[2])
fileVar.remove(accessedAccount[1])
fileVar.remove(accessedAccount[0])
f.write(accessedAccount[0] + "\n")
f.write(accessedAccount[1] + "\n")
newBalance = str(newBalance)
f.write(newBalance + "\n")
for item in fileVar:
f.write("%s\n" %item)
test = raw_input("Waiting for input")
if choice2 == "w":
amount = int(raw_input("How much money would you like to withdraw? Current balanace: %i : " %intBalance))
newBalance = intBalance - amount
print "Current Balance: %i" %newBalance
f.close()
os.remove("accounts.txt")
f = open ("accounts.txt", "a+")
fileVar.remove(accessedAccount[0])
fileVar.remove(accessedAccount[1])
fileVar.remove(accessedAccount[2])
f.write(accessedAccount[0] + "\n")
f.write(accessedAccount[1] + "\n")
newBalance = str(newBalance)
f.write(newBalance + "\n")
for item in fileVar:
f.write("%s\n" %item)
test = raw_input("Waiting for input")
if choice == "r":
removeChoice = raw_input("What is the name of the account you wish to remove?: ")
f.close()
os.remove("accounts.txt")
f= open("accounts.txt", "a+")
for i, line in enumerate(fileVar):
if removeChoice in line:
for j in fileVar[i:i+3]:
accessedAccount.append(j)
fileVar.remove(accessedAccount[0])
fileVar.remove(accessedAccount[1])
fileVar.remove(accessedAccount[2])
for item in fileVar:
f.write("%s\n" %item)
f.close()
for example, the original text file looks like this:
Ryan
Savings
0
John
Chequings
0
Carly
Savings
0
when it is re-written with edited information, what it is supposed to look like, if 300 dollars were added to Carly's account:
Carly
Savings
300
Ryan
Savings
0
John
Chequings
0
What it looks like instead:
Carly
Savings
300
John
Chequings
Ryan
0
Savings
0
Thank you in advance :)
Not a direct answer to your question, but some pointers which may end up making it much easier for both yourself and others to debug your code.
1) Functions are your friend. See if you can take small tasks and break them up into functions. For example, writing out someone's balance to a file could be a small function, which you might call like:
def write_balance_to_file(account_details):
...function code goes here...
account_details = {name:"Ryan", account:"Savings", balance:1000}
write_balance_to_file(account_details)
Opening and closing the file should be handled within that function, and preferably using:
with open('filename', 'a+') as f:
f.write("A thing to write")
Note that you don't need to close the file manually when doing this.
2) Use a dictionary for storing a person's account details, rather than a list. Multiple accounts can be stored as a list of dictionaries. This makes it a lot easier to read as call such as:
f.write(accessedAccount[0] + "\n")
which becomes:
f.write(accessedAccount['name'] + '\n')
You can then pass in this dictionary to the write_balance_to_file method you will create. :)
3) Consider a tab-separated format for your accounts.txt file. Remember to escape/remove any tabs in your user input. This way each account will be on one line.
4) Possibly a little way in the future for you, but be aware that unit-testing exists, and is good practice. In essence, you can write tests (usually using a test framework such as py.test) which test each function/class/module under different input conditions. Anything that you can't break up into small, testable code fragments (functions or classes) is probably not good code. Writing tests is a great way to identify bugs in your code, and often helps to clarify your thinking. ALWAYS TEST!
For a minimal change that will solve the issue, this is the code that needs to change:
for i, line in enumerate(fileVar):
if account in line:
for j in fileVar[i:i+3]:
print j
accessedAccount.append(j)
This records which entries are part of the accessedAccount however later on you just remove the first occurence of these entries:
fileVar.remove(accessedAccount[2])
fileVar.remove(accessedAccount[1])
fileVar.remove(accessedAccount[0])
but if the entry is something as simple as 0 then it will not necessarily remove it from the correct place, so instead pop the accessed account out of the fileVar when putting them into accessedAccount:
for i, line in enumerate(fileVar):
if account in line:
for j in range(3):
print i+j
accessedAccount.append(fileVar.pop(i+j))
#break # you probably want to stop checking by this point
This will remove the relevent lines from fileVar and put them in accessedAccount so the order of lines will not be messed up by using .remove, and then obviously comment out the calls to .remove:
## fileVar.remove(accessedAccount[2])
## fileVar.remove(accessedAccount[1])
## fileVar.remove(accessedAccount[0])
This should fix the immediate problem of taking out the wrong lines.
I am producing a small recipe input and output program in Python, however I am having trouble writing the ingredients to a CSV file. I am trying to print each item of a list to a comma separated file, using this code:
with open('recipes/' + recipeName + '.csv', 'w') as csvfile:
recipewriter = csv.writer(csvfile)
recipewriter.write(ingredientList[0])
recipewriter.write(ingredientList[1])
recipewriter.write(ingredientList[2])
In the list, there are three items. For example, this could be a list I am trying to save to a file:
ingredientList = ['flour', '500', 'g']
And I want the data to appear like this in a CSV file:
flour,
500,
g,
Instead it is appearing like this:
f,l,o,u,r,
5,0,0,
g,
How do I get it to appear in my desired format?
Here is my source code:
#Python 3.3.3
import sys #Allows use of the 'exit()' function
import csv #Allows use of the CSV File API
def mainMenu():
print("########################################################")
print("# Welcome to the recipe book, please select an option: #")
print("# 1. Add new recipe #")
print("# 2. Lookup existing recipe #")
print("# 3. Exit #")
print("########################################################")
selectedOption = None
inputtedOption = input()
try:
inputtedOption = int(inputtedOption)
except ValueError:
print("Invalid option entered")
if inputtedOption == 1:
selectedOption = inputtedOption
elif inputtedOption == 2:
selectedOption = inputtedOption
elif inputtedOption == 3:
print("Exiting...")
sys.exit(0)
return selectedOption
def validateInput(inputtedData):
try: #Test if data is an integer greater than 1
inputtedData = int(inputtedData)
if int(inputtedData) < 1: #Recipes cannot contain less than 1 ingredient
print("Sorry, invalid data entered.\n('%s' is not valid for this value - positive integers only)" % inputtedData)
return False
return int(inputtedData)
except ValueError:
print("Sorry, invalid data entered.\n('%s' is not valid for this value - whole integers only [ValueError])\n" % inputtedData)
return False
def addRecipe():
print("Welcome to recipe creator! The following questions will guide you through the recipe creation process.\nPlease enter the name of your recipe (e.g. 'Pizza'):")
recipeName = input()
print("Recipe Name: %s" % recipeName)
print("Please enter the amount of people this recipe serves (e.g. '6'):")
recipeServingAmount = input()
if validateInput(recipeServingAmount) == False:
return
else:
recipeServingAmount = validateInput(recipeServingAmount)
print("Recipe serves: %s" % recipeServingAmount)
print("Please enter the number of ingredients in this recipe (e.g. '10'):")
recipeNumberOfIngredients = input()
if validateInput(recipeNumberOfIngredients) == False:
return
else:
recipeNumberOfIngredients = validateInput(recipeNumberOfIngredients)
print("Recipe contains: %s different ingredients" % recipeNumberOfIngredients)
ingredientList = {}
i = 1
while i <= recipeNumberOfIngredients:
nthFormat = "st"
if i == 2:
nthFormat = "nd"
elif i == 3:
nthFormat = "rd"
elif i >= 4:
nthFormat = "th"
ingredientNumber = str(i) + nthFormat
print("Please enter the name of the %s ingredient:" % ingredientNumber)
ingredientName = input()
print("Please enter the quantity of the %s ingredient:" % ingredientNumber)
ingredientQuantity = input()
print("Please enter the measurement value for the %s ingredient (leave blank for no measurement - e.g. eggs):" % ingredientNumber)
ingredientMeasurement = input()
print("%s ingredient: %s%s %s" % (ingredientNumber, ingredientQuantity, ingredientMeasurement, ingredientName))
finalIngredient = [ingredientName, ingredientQuantity, ingredientMeasurement]
print(finalIngredient[1])
ingredientList[i] = finalIngredient
with open('recipes/' + recipeName + '.csv', 'w') as csvfile:
recipewriter = csv.writer(csvfile)
recipewriter.write(ingredientList[0])
recipewriter.write(ingredientList[1])
recipewriter.write(ingredientList[2])
i = i + 1
def lookupRecipe():
pass # To-do: add CSV reader and string formatter
#Main flow of program
while True:
option = mainMenu()
if option == 1:
addRecipe()
elif option == 2:
lookupRecipe()
csv.writers don't have a write() method. In Python 3 you could do it like this:
with open('recipes/' + recipeName + '.csv', 'w', newline='') as csvfile:
recipewriter = csv.writer(csvfile)
recipewriter.writerow([ingredientList[0]])
recipewriter.writerow([ingredientList[1]])
recipewriter.writerow([ingredientList[2]])
Simplest way is to just call join on the list adding a , and a newline and forget about using the csv module:
with open('recipes/{}.csv'.format(recipeName), 'w') as csvfile:
csvfile.write(",\n".join(ingredientList))
Output:
flour,
500,
g
I presume you are actually using writerow not write as csv.writer has no write method.
The reason you see f,l,o,u,r, is because csv.writer.writerow expects an iterable so when you pass the string it iterates over and writes each character individually.
You would need to use recipewriter.writerow([ingredientList[0]]), wrapping the string in a list.
That will still not actually add any trailing comma after the end of your strings.
If you want a trailing comma after each line including the last:
with open('recipes/{}.csv'.format("foo"), 'w') as csvfile:
for ele in ingredientList:
csvfile.write("{},\n".format(ele))
Output:
flour,
500,
g,
If you want a useful csv you may be better making each it's own column or just writing each to their own line:
import csv
with open('{}.csv'.format("foo"), 'w') as csvfile:
recipewriter = csv.writer(csvfile)
recipewriter.writerow(ingredientList)
Output:
flour,500,g
Or on individual lines without the trailing comma:
with open('{}.csv'.format("foo"), 'w') as csvfile:
recipewriter = csv.writer(csvfile)
for ele in ingredientList:
recipewriter.writerow([ele])
Output:
flour
500
g