【问题标题】:Python: Write list to file, line by linePython:逐行将列表写入文件
【发布时间】:2017-05-21 01:58:36
【问题描述】:

我想将以下list 写入文件,每次都从新行开始。

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

【问题讨论】:

  • 为什么要将代码格式化为字符串?
  • 这里已经回答了:stackoverflow.com/questions/899103/…
  • @famargar,我也试过了,但for item in thelist: thefile.write("%s\n" % item) 也会覆盖文件,否则我做错了什么(
  • @AndrewJaffe,是的,没有意义,我改变格式

标签: python list file


【解决方案1】:

我认为您正在为缓冲参数寻找“a”而不是“w”:

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

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

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2012-12-17
  • 2018-06-15
  • 2018-08-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多