我正在尝试将我的字典写入文件并且已经知道我必须将其更改为字符串。但是,有什么方法可以在末尾添加 '\n' 以保持我的文件井井有条吗?
代码如下:
def dictionary(grocerystock):
with open('grocery_stock.txt','r+') as f:
lines = f.readlines()
# filter out empty lines
lines = [line for line in lines if line.strip() != '']
# split all lines
lines = [line.split() for line in lines]
# convert to a dictionary
grocerystock = dict((a, (b, c)) for a, b, c in lines)
# print
for k, v in grocerystock.items():
print (k, v)
grocerystock=str(grocerystock)
grocerystock=grocerystock.replace("{",'')
grocerystock=grocerystock.replace("}",'')
grocerystock=grocerystock.replace("(",'')
grocerystock=grocerystock.replace(")",'')
grocerystock=grocerystock.lstrip()
grocerystock=grocerystock.rstrip()
grocerystock=grocerystock.strip()
grocerystock=grocerystock.replace(":",'')
c=(grocerystock+("\n"))
e=open('grocery_stock.txt', 'w+')
e.write(c)
e.close()
任何帮助将不胜感激。