2017-01-06 11 views
0

私は次のように書いています。listは、新しい行から毎回ファイルに書きます。Python:リストをファイルごとに書き出します。

bill_List = [total_price, type_of_menu, type_of_service, amount_of_customers, discount] 

このコードを使用しようとしましたが、テキストファイルが上書きされました。誰かが私を助けることができますか?私のミスはどこですか?

# attempt #1 
f = open("Bills.txt", "w") 
f.write("\n".join(map(lambda x: str(x), bill_List))) 
f.close() 


# attempt #2 
# Open a file in write mode 
f = open('Bills.txt', 'w') 
for item in bill_List: 
f.write("%s\n" % item) 
# Close opend file 
f.close() 

# attempt #3 

with open('Bills.txt', 'w') as f: 
for s in bill_List: 
    f.write(s + '\n') 

with open('Bills.txt', 'r') as f: 
bill_List = [line.rstrip('\n') for line in f] 

# attempt #4 
with open('Bills.txt', 'w') as out_file: 
out_file.write('\n'.join(
    bill_List)) 
+0

は、なぜあなたは文字列としてあなたのコードの書式を設定していますか? –

+2

これは既にここで答えられています:http://stackoverflow.com/questions/899103/writing-a-list-to-a-file-with-python – famargar

+0

@famargar、私もこれを試しましたが、 thefile.write( "%s \ n"%item) "ファイルを上書きするか、何かが間違っている( –

答えて

1

私はあなたが「」の代わりにバッファリングパラメータに「W」の探していると思う:

with open('Bills.txt', 'a') as out_file: 
    [...] 

https://docs.python.org/2/library/functions.html?highlight=open#open

+0

ああ、とても簡単な間違い。 !!! –

+1

問題はありません。あなたがいる間、 'writelines()'も考慮してください:https://docs.python.org/2/library/stdtypes.html?highlight=writelines#file.writelines(私はそうではありませんあなたのケースに当てはまることを確かめてください) – lorenzog

関連する問題