[英]How do I get my dictionary to begin a new line when writing code to a file from a program?
这是我的代码示例,下面是我正在尝试做的示例。 预先感谢您的帮助。
cards = {}
import sys
n = 0
while True:
n += .01
cards[n] = {'name': str(input('Please enter name: ')),
'year': int(input('Please enter a year: ')),
'brand': str(input('Please enter a brand: ')),
'make': str(input('Please enter a make: ')),
'parallel': (input('parallel - Y OR N? ')),
'auto': (input('auto - Y OR N? ')),
'rookie_card': (input('rookie card - Y OR N? ')),
'numbered': (input('numbered - Y OR N? ')),
'card_num': input('Please enter a card number: '),
}
# 'parallel_type':
# 'serial_num':
print(cards)
while True:
choice = input('Press Y to continue or N to exit: ').capitalize()
if choice == 'Y':
break
elif choice == 'N':
print('Next input n = ', n)
try:
cards_file = open('cards_file.py', 'wt')
cards_file.write(str(cards))
cards_file.close()
except:
print('Unable to write to file')
sys.exit()
else:
print('Please enter a valid option!')
这就是我正在使用的。 每次我的程序写入 card_file.py 时,我都希望字典像这样开始一个新行:
cards = {1: {'name':'some_name', 'year': 'some_year', 'brand': 'brand'},
------->{2: { -------------------new line of data---------------------}
}
代替
cards_file.write(str(cards))
和
for k,v in cards.items():
cards_file.write(f'{k} : {v}\n')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.