我制作了一个类似于RPG stat创建者的游戏。但是,作为分配的一部分,您必须将统计信息打印到* .txt文件中。
我使用这个网站已经做到了这一点:
http://www.afterhoursprogramming.com/tutorial/Python/Writing-to-Files/
守则是:
f = open("test.txt","a") #opens file with name of "test.txt"
f.write("The Name of the Character is" ,name,)
[Leave Line]
[Leave Line]
f.write("Class")
[Leave Line]
f.write("Strength /100:" ,strength,)
[Leave Line]
f.write("Magic /100:" ,magic,)
[Leave Line]
f.write("Dexterity /100: ,dexterity, ")
[Leave Line]
f.write("Extra Ability is...." ,extraability,)
f.close()
但我不知道如何在每个统计数据后留下一条线。最终结果应如下所示:
'某事',只是我所做的变数。
非常感谢帮助!
答案 0 :(得分:0)
同一个教程显示了问题所在 - 你错过了一个" \ n"在您写入文件的字符串的末尾。对于空行,只需编写" \ n"。
要将变量作为输出字符串的一部分包含在内,您有许多选项 - 这是一个很好的例子here.
答案 1 :(得分:0)
正如其他人已经说过的,你真正的问题是缺少“\ n”。也就是说,我认为比单独为每行添加“\ n”更好的解决方案是在列表中写下您想要的内容,然后使用str.join
:
content = [
"The Name of the Character is" + name + "\n", # As first line has an extra blank line, this will be the only one with the explicit "\n"
"Strength /100:" + strength,
...
]
base_name = "Frodo"
with open(base_name + ".txt","a") as f:
f.write("\n".join(content)) # Maybe "\n\n" since you want a blank line between each attribute.
这应该可以做到!
答案 2 :(得分:0)
您可以在一个文件中执行此操作,如下所示:
with open("test.txt", "a") as f: #opens file with name of "test.txt"
dPlayer = {
"name" : "Bob",
"class" : "Wizard",
"strength" : 50,
"magic" : 30,
"dexterity" : 85,
"extraability" : "speed"}
output = """The Name of the Character is {name}
Class: {class}
Strength: {strength}/100
Magic: {magic}/100
Dexterity: {dexterity}/100
Extra Ability is....{extraability}
"""
f.write(output.format(**dPlayer))
这会给你一个输出文件,如:
The Name of the Character is Bob
Class: Wizard
Strength: 50/100
Magic: 30/100
Dexterity: 85/100
Extra Ability is....speed
我已将播放器的详细信息存储到单个字典中,并且键可用作字符串中的占位符。通过使用带有三引号的多行字符串,可以非常轻松地根据需要格式化输出。
此外,通过使用with
语句,文件将在之后自动关闭。
如果您不想使用字典(或更新的格式化方法),您可以使用以下内容,但需要格外小心以确保所有参数都符合字符串的顺序。
with open("test.txt", "a") as f: #opens file with name of "test.txt"
name = "Bob"
player_class = "Wizard"
strength = 50
magic = 30
dexterity = 85
extraability = "speed"
player = (name, player_class, strength, magic, dexterity, extraability)
output = """The Name of the Character is %s
Class: %s
Strength: %d/100
Magic: %d/100
Dexterity: %d/100
Extra Ability is....%s
""" % player
f.write(output)
使用Python 2.7进行测试