NameError:在python脚本中打开文件时未定义全局名称'w'?

时间:2013-12-16 13:33:38

标签: python

当我运行我的代码(下面)时,在打开文件时会出现错误NameError: global name 'w' is not defined

我不知道为什么会这样做因为'w'是如何写文件的,它不是变量?

import random
import math

def var():
    strength = 10
    skill = 10
    dice4 = 0
    dice12 = 0
    dice_score = 0

    character_name = str(input("Please enter your characters name: "))
    skill_func(strength, skill, dice4, dice12, character_name, dice_score)

def skill_func(strength, skill, dice4, dice12, character_name, dice_score):

    print(character_name + "'s attributes are being generated! ... ")

    dice4, dice12 = random.randrange(1,4), random.randrange(1,12) 

    dice_score = dice12/dice4
    dice_score = math.floor(dice_score)
    skill = skill + dice_score

    strength_func(strength, skill, dice4, dice12, character_name, dice_score)

def strength_func(strength, skill, dice4, dice12, character_name, dice_score):
    dice4, dice12 = random.randrange(1,4), random.randrange(1,12) 

    dice_score = dice12/dice4
    dice_score = math.floor(dice_score)
    strength = strength + dice_score
    file(strength, skill, dice4, dice12, character_name)

def file(strength, skill, dice4, dice12, character_name):
    file = open("N:\Controlled Assessment - James Barham\Task Two\attributes.txt", w)
    file.writelines(character_name + " - Strength = " + str(strength) + ", Skill = " + str(skill))

var()

1 个答案:

答案 0 :(得分:4)

这:

file = open("N:\Controlled Assessment - James Barham\Task Two\attributes.txt", w)

应该是这样的:

file = open("N:\Controlled Assessment - James Barham\Task Two\attributes.txt", "w")