当从程序向文件中写入代码时,如何使字典开始新行



这是我的代码示例,下面是我尝试做的一个示例。提前感谢您的帮助。

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!')

这就是我正在处理的问题。每次我的程序写到cards_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') 

最新更新