0

所以我昨天发布了这段代码的另一部分,但我遇到了另一个问题。我为 RPG 制作了一个字符生成器,​​我试图让程序将字符表函数的输出输出到 .txt 文件,但我认为发生的事情是该函数可能会返回None一些统计数据的值(这完全是正常,)然后当我尝试写入 .txt 文件时出现错误。我完全被难住了,非常感谢您的帮助!

# Character Sheet Function.
def char_shee():
    print "Name:", name
    print "Class:", character_class
    print "Class Powers:", class_power
    print "Alignment:", alignment
    print "Power:", pow, pow_mod()
    print "Intelligence:", iq, iq_mod()
    print "Agility:", agi, agi_mod()
    print "Constitution:", con, con_mod()
    print "Cynicism:", cyn, cyn_mod()
    print "Charisma:", cha, cha_mod()
    print "All Characters Start With 3 Hit Dice"
    print"""
\t\t{0}'s History
\t\t------------------
\t\tAge:{1}
\t\t{2}
\t\t{3}
\t\t{4}
\t\t{5}
\t\t{6}
\t\t{7}
\t\t{8}
\t\t{9}
\t\tGeneral Disposition: {10}
\t\tMost important thing is: {11}
\t\tWho is to blame for worlds problems: {12}
\t\tHow to solve the worlds problems: {13}
""".format(name, age, gender_id, ethnic_pr, fcd, wg, fogo_fuck, cur_fam,fam_fuk, nat_nur, gen_dis, wha_wor, who_pro, how_pro)

char_shee()
print "Press enter to continue"
raw_input()

# Export to text file? 
print """Just because I like you, let me know if you want this character
saved to a text file. Please remember if you save your character not to 
name it after something important, or you might lose it. 
"""
text_file = raw_input("Please type 'y' or 'n', if you want a .txt file")
if text_file == "y":
    filename = raw_input("\nWhat are we calling your file, include .txt")
    target = open(filename, 'w')
    target.write(char_shee()
    target.close
    print "\nOk I created your file."
    print """
Thanks so much for using the Cyberpanky N.O.W Character Generator
By Ray Weiss
Goodbye
"""
else:
    print """
Thanks so much for using the Cyberpanky N.O.W Character Generator
By Ray Weiss
Goodbye
"""

编辑:这是我得到的输出:

> Please type 'y' or 'n', if you want a .txt filey
> 
> What are we calling your file, include .txt123.txt <function char_shee
> at 0x2ba470> Traceback (most recent call last):   File "cncg.py", line
> 595, in <module>
>     target.write(pprint(char_shee)) TypeError: must be string or read-only character buffer, not None
4

2 回答 2

3

使用printwrites to sys.stdout,它不会返回值。

您想要char_shee返回字符表字符串以将其写入文件,您只需构建该字符串即可。

为了简化字符串的构建,请使用列表来收集字符串:

def char_shee():
    sheet = []
    sheet.append("Name: " + name)
    sheet.append("Class: " + character_class)
    # ... more appends ...

    # Return the string with newlines
    return '\n'.join(sheet)
于 2012-09-25T12:26:33.043 回答
1

您在这里忘记了括号:

target.write(char_shee())
target.close()

正如@Martijn Pieters 指出的那样,您应该从 中返回值char_shee(),而不是打印它们。

于 2012-09-25T12:26:06.843 回答