我正在 Python 中制作一个小的食谱输入和输出程序,但是我在将成分写入 CSV 文件时遇到了麻烦。我正在尝试使用以下代码将列表中的每个项目打印到逗号分隔文件:
with open('recipes/' + recipeName + '.csv', 'w') as csvfile:
recipewriter = csv.writer(csvfile)
recipewriter.write(ingredientList[0])
recipewriter.write(ingredientList[1])
recipewriter.write(ingredientList[2])
在列表中,有三个项目。例如,这可能是我试图保存到文件的列表:
ingredientList = ['flour', '500', 'g']
我希望数据在CSV文件中显示如下:
flour,
500,
g,
相反,它看起来像这样:
f,l,o,u,r,
5,0,0,
g,
如何让它以我想要的格式显示?
这是我的源代码:
#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()
答案 0 :(得分:2)
csv.writer
没有write()
方法。在Python 3中你可以这样做:
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]])
答案 1 :(得分:0)
最简单的方法是在列表中调用join,添加,
和换行符,忘记使用csv模块:
with open('recipes/{}.csv'.format(recipeName), 'w') as csvfile:
csvfile.write(",\n".join(ingredientList))
输出:
flour,
500,
g
我认为你实际上在使用writerow
而不是写csv.writer
没有写方法。
您看到f,l,o,u,r,
的原因是因为csv.writer.writerow
期望迭代,所以当您传递字符串时,它会迭代并单独写入每个字符。
您需要使用recipewriter.writerow([ingredientList[0]])
,将字符串包装在列表中。
在字符串结束后,实际上仍然不会添加任何尾随逗号。
如果你想在每行后面都有一个逗号,包括最后一行:
with open('recipes/{}.csv'.format("foo"), 'w') as csvfile:
for ele in ingredientList:
csvfile.write("{},\n".format(ele))
输出:
flour,
500,
g,
如果你想要一个有用的csv,你可能会更好地制作每个自己的专栏,或者只是将它们写成自己的专栏:
import csv
with open('{}.csv'.format("foo"), 'w') as csvfile:
recipewriter = csv.writer(csvfile)
recipewriter.writerow(ingredientList)
输出:
flour,500,g
或在没有逗号的单行上:
with open('{}.csv'.format("foo"), 'w') as csvfile:
recipewriter = csv.writer(csvfile)
for ele in ingredientList:
recipewriter.writerow([ele])
输出:
flour
500
g