简体   繁体   English

在 Python 中将包含整数和字符串的列表写入文件

[英]Writing a list including integers and strings to a file in Python

I have a real stickler of a dilemma I need y'all to solve.我有一个真正的困境,需要你们解决。

I need quantities my program to write a list of products and quantities to a text file.我需要数量我的程序将产品和数量列表写入文本文件。

I've gotten this far:我已经走了这么远:

file = open("Orders.txt", "w")
file.write("Stock we require \n")
file.write("Chips Needed:")
file.write(str(order1))
file.write("\n")
file.write("Juice Needed:")
file.write(str(order2))
file.close()

order1 and order2 are integers order1 和 order2 是整数

This is what this code produces in the Orders.txt:这是此代码在 Orders.txt 中生成的内容:

Stock we require
Chips Needed:39Juice Needed:0

(Where order1 was 39 and order2 was 0) (其中 order1 为 39,order2 为 0)

I want:我想要:

Stock we require:

Chips
(order1)

Juice
(order2)

Use .format :使用.format

with open("Orders.txt", "w") as file:
    file.write("Stock we require:\n")
    file.write("Chips ({})\n".format(order1))
    file.write("Juice ({})\n".format(order2))

You can easily change the format this way.您可以通过这种方式轻松更改格式。

Also note the usage of with .还要注意with的用法。

对于这种情况,您可以考虑file.writelines(line1,line2,...)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM