[英]Best way to save data to a file?
def saveFood():
print('Enter food name')
foodNameS = input().upper()
print('Enter calories')
foodCalS = input()
print('Enter protein')
foodProteinS = input()
print('Enter fat')
foodFatS = input()
print('Enter carb')
foodCarbS = input()
print(foodNameS + '\n' + 'calorie ' + foodCalS + '\n' + 'protein ' +
foodProteinS + '\n' + 'fat ' + foodFatS + '\n' + 'carbs ' + foodCarbS)
print('Confirm? Y/N')
while True:
confirmation = input().upper()
if confirmation == 'Y' or confirmation == 'N':
if confirmation == 'Y':
text_file = open(("FoodList.txt"), "a")
text_file.write('' + "\n")
text_file.write('\n' + 'Food: ' + foodNameS.lower() + "\n")
text_file.write('cal ' + foodCalS + "\n")
text_file.write('protein ' + foodProteinS + "\n")
text_file.write('fat ' + foodFatS + "\n")
text_file.write('carb ' + foodCarbS)
text_file.close()
askOption()
break
else:
askOption()
this is currently my code in a calorie tracking app i have.这是目前我在卡路里跟踪应用程序中的代码。 However when deleting items from the list it becomes very awkward and ugly.
然而,当从列表中删除项目时,它变得非常尴尬和难看。 I tried json but deleting and adding extra stuff was also weird and awkward.
我试过 json 但删除和添加额外的东西也很奇怪和尴尬。 What can i do to tackle this?
我能做些什么来解决这个问题? I tried shelve but it seemed inefficient.
我试过搁置,但似乎效率低下。
I would use f-strings for readability.我会使用 f-strings 来提高可读性。
Here an example这里有一个例子
report = f'''
Food: {foodNameS.lower()}
cal {foodCalS}
protein {foodProteinS}
fat {foodFatS}
carb {foodCarbS}
'''
with open("FoodList.txt", "a") as f:
f.write(report)
Try to use json
maybe.尝试使用
json
可能。
And try to open files with with
并尝试使用
with
打开文件
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.