Output file in Python

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • BurnTard
    New Member
    • May 2007
    • 52

    Output file in Python

    Hello, I'm back.

    After lots of tinkering, and asking guys here at the forum, we made a program that could successfully create a dungeons and dragons role playing character. In the end, the output looks like this:

    ----------------------------------------------------------------
    Your character's sex is: Male
    Your character's name is: Charlie
    Your character's race is: Gnome
    Your character's class is: Warrior
    ----------------------------------------------------------------
    .............Ph ysical Traits......... ...
    strength = 14
    decterity = 15
    constitution = 10
    .............Me ntal Traits......... ......
    intelligence = 10
    charisma = 9
    wisdom = 8
    ----------------------------------------------------------------
    Alignment: Chaotic Neutral



    And that is in cmd of course.
    The thing I was wondering was this, is it possible to write something into the python script to make it save this output as a .txt file?

    Thanks, now I'm off to a birthday!
  • bvdet
    Recognized Expert Specialist
    • Oct 2006
    • 2851

    #2
    Originally posted by BurnTard
    Hello, I'm back.

    After lots of tinkering, and asking guys here at the forum, we made a program that could successfully create a dungeons and dragons role playing character. In the end, the output looks like this:

    ----------------------------------------------------------------
    Your character's sex is: Male
    Your character's name is: Charlie
    Your character's race is: Gnome
    Your character's class is: Warrior
    ----------------------------------------------------------------
    .............Ph ysical Traits......... ...
    strength = 14
    decterity = 15
    constitution = 10
    .............Me ntal Traits......... ......
    intelligence = 10
    charisma = 9
    wisdom = 8
    ----------------------------------------------------------------
    Alignment: Chaotic Neutral



    And that is in cmd of course.
    The thing I was wondering was this, is it possible to write something into the python script to make it save this output as a .txt file?

    Thanks, now I'm off to a birthday!
    Yes. This code[code=Python]fn = r'X:\subdirecto ry\data.txt'
    data = ['sex', 'name', 'race', 'class', 'strength', 'dexterity', 'constitution', 'intelligence', 'charisma', 'wisdom']
    dd = dict.fromkeys(d ata, 'XX')
    outList = ['%s = %s' % (item, dd[item]) for item in data]
    f = open(fn, 'w')
    f.write('\n'.jo in(outList))
    f.close()[/code]yields a file like this:

    sex = XX
    name = XX
    race = XX
    class = XX
    strength = XX
    dexterity = XX
    constitution = XX
    intelligence = XX
    charisma = XX
    wisdom = XX


    I'll leave it to you to pretty up the output.

    Comment

    • ghostdog74
      Recognized Expert Contributor
      • Apr 2006
      • 511

      #3
      or if its just one file, do it from the command line
      Code:
      # python script.py > outfile.txt

      Comment

      • BurnTard
        New Member
        • May 2007
        • 52

        #4
        Originally posted by bvdet
        Yes. This code[code=Python]fn = r'X:\subdirecto ry\data.txt'
        data = ['sex', 'name', 'race', 'class', 'strength', 'dexterity', 'constitution', 'intelligence', 'charisma', 'wisdom']
        dd = dict.fromkeys(d ata, 'XX')
        outList = ['%s = %s' % (item, dd[item]) for item in data]
        f = open(fn, 'w')
        f.write('\n'.jo in(outList))
        f.close()[/code]yields a file like this:

        sex = XX
        name = XX
        race = XX
        class = XX
        strength = XX
        dexterity = XX
        constitution = XX
        intelligence = XX
        charisma = XX
        wisdom = XX


        I'll leave it to you to pretty up the output.
        That is probably good and all, but I have this insane theory that I will not get better at programming by just copying and pasting... Is that crazy? If you would please explain the different parts of that? Like the ones that are one step beyond basic? I'm a newbie, like it says under my name... If that saounded rude, it was unintentional.

        Thanks

        Comment

        • bvdet
          Recognized Expert Specialist
          • Oct 2006
          • 2851

          #5
          Originally posted by BurnTard
          That is probably good and all, but I have this insane theory that I will not get better at programming by just copying and pasting... Is that crazy? If you would please explain the different parts of that? Like the ones that are one step beyond basic? I'm a newbie, like it says under my name... If that sounded rude, it was unintentional.

          Thanks
          You seem to have the right attitude, wanting to learn how it works. Writing information to a file is easy. Compiling the information to write to a file in a structured manner is not so easy (sometimes). Do you want to be able to read in the data at a later date? If so, it must be organized in a manner that will be easy to parse. I will explain my code, line for line.

          This is the name of the file that we will write to:[code=Python]fn = r'X:\subdirecto ry\data.txt'[/code]This is a list of variable names:[code=Python]data = ['sex', 'name', 'race', 'class', 'strength', 'dexterity', 'constitution', 'intelligence', 'charisma', 'wisdom'][/code]A dictionary is probably the best way to organize data in many cases. The dictionary is Python's built-in mapping type object. The mapping type of object is also known as a hash table or associative array. We can initialize a dictionary to maintain your data in your program like this:[code=Python]dd = dict.fromkeys(d ata, 'XX')[/code]A player's attributes can be set like this:[code=Python]>>> dd
          {'dexterity': 'XX', 'strength': 'XX', 'name': 'XX', 'intelligence': 'XX', 'sex': 'XX', 'charisma': 'XX', 'race': 'XX', 'wisdom': 'XX', 'class': 'XX', 'constitution': 'XX'}
          >>> dd['strength']=10
          >>> dd
          {'dexterity': 'XX', 'strength': 10, 'name': 'XX', 'intelligence': 'XX', 'sex': 'XX', 'charisma': 'XX', 'race': 'XX', 'wisdom': 'XX', 'class': 'XX', 'constitution': 'XX'}
          >>> print dd['strength']
          10
          >>> [/code]When you have gathered all of the player's data, create a list of formatted strings suitable for writing to disk:[code=Python]>>> outList = ['%s = %s' % (item, dd[item]) for item in data]
          >>> outList[4]
          'strength = 10'
          >>> [/code]Create a file object for writing:[code=Python]f = open(fn, 'w')[/code]join is a string method that is used to assemble a list of strings into a single string. I have chosen this method to further prepare the data for writing. Here's an example of the use of join:[code=Python]>>> strList = ["This is one sentence.", "This is another sentence."]
          >>>'\n'.join(st rList)
          >>> print '\n'.join(strLi st)
          This is one sentence.
          This is another sentence.
          >>> [/code]I am now writing the data to the file:[code=Python]f.write('\n'.jo in(outList))[/code]Close the file object:[code=Python]f.close()[/code]This will read the data back in:[code=Python]>>> dd1 = {}
          >>> for item in open(fn).readli nes():
          ... key, value = item.strip().sp lit(' = ')
          ... dd1[key] = value
          ...
          >>> for key in dd1:
          ... print '%s=%s' % (key, dd1[key])
          ...
          dexterity=XX
          strength=10
          name=XX
          intelligence=XX
          sex=XX
          charisma=XX
          race=XX
          wisdom=XX
          class=XX
          constitution=XX
          >>> [/code]

          Comment

          • BurnTard
            New Member
            • May 2007
            • 52

            #6
            [CODE=python]'%s'='%s'[/CODE]
            ... is the only thing that I still don't understand. I was without internet for some time, and bored out of my mind I tried to force pyton into telling me what those things did... it wasn't all easy... was rather hard to get the exact __doc__ for write, since it just wrote to the file, instead of giving info... This is what I made when I gave up understanding " '%s'='%s' ":

            I'm posting the entire script, so it's rather a lot


            [Code=python]

            sex=raw_input(" First, which sex do you want your character to be? ")
            name=raw_input( 'What do you want to call your character? ')

            import random

            print ""
            print ""

            figures=[]
            for n in range(6):
            dice=[random.randint( 1,6) for i in range(4)]
            dice.sort()
            d2=dice[1:]
            figures.append( d2[0]+d2[1]+d2[2])

            print figures

            print ""

            print """These are random numbers given by the dice,
            you must now chose where to put them.
            This will affect your game, and you should bear in mind
            what kind of character you want to create."""


            print ""
            print ""

            strength=int(ra w_input("""Whic h one of them will you assign to strength?
            Strength is a measure of muscle, endurance and stamina combined.
            Strength affects the ability of characters to lift and carry weights and make effective melee attacks. """))

            if int(strength) in figures:
            figures.remove( strength)
            else:
            print "Don't try to cheat! Naughty! Everlasting curses upon thee!!"
            while 1<2:
            print "Cheater!"
            print ""

            print ""
            print ""
            print figures
            print ""
            print ""


            dexterity=int(r aw_input("""Whi ch of them will you assign to Dexterity?
            Dexterity encompasses a number of physical attributes including
            hand-eye coordination, agility, reflexes, fine motor skills,
            balance and speed of movement;
            a high dexterity score indicates superiority in all these attributes.
            Dexterity affects characters with regard to initiative in attack,
            the projection of missiles from hand or other means,
            and in defensive measures. Dexterity is the ability most influenced by
            outside influences (such as armor) """))

            if int(dexterity) in figures:
            figures.remove( dexterity)
            else:
            print "Don't try to cheat! Naughty! Everlasting curses upon thee!!"
            while 1<2:
            print "Cheater!"
            print ""

            print ""
            print ""
            print figures
            print ""
            print ""



            constitution=in t(raw_input(""" Which of them will you assign to Constitution?
            Constitution is a term which encompasses the character's physique,
            toughness, health and resistance to disease and poison.
            The higher a character's Constitution, the more hit points
            that character will have. Unlike the other ability scores,
            which knock the character unconscious when they hit 0,
            having 0 Constitution is fatal. """))

            if int(constitutio n) in figures:
            figures.remove( constitution)
            else:
            print "Don't try to cheat! Naughty! Everlasting curses upon thee!!"
            while 1<2:
            print "Cheater!"
            print ""


            print ""
            print ""
            print figures
            print ""
            print ""



            intelligence=in t(raw_input(""" Which of them will to assign to Intelligence?
            Intelligence is similar to IQ, but also includes mnemonic ability,
            reasoning and learning ability outside those measured by the written word.
            Intelligence dictates the number of languages a character
            can learn and the number of spells a Wizard may know. """))

            if int(intelligenc e) in figures:
            figures.remove( intelligence)
            else:
            print "Don't try to cheat! Naughty! Everlasting curses upon thee!!"
            while 1<2:
            print "Cheater!"
            print ""


            print ""
            print ""
            print figures
            print ""
            print ""



            wisdom=int(raw_ input("""Which of them will you assign to Wisdom?
            Wisdom is a composite term for the characters enlightenment,
            judgement, wile, willpower and intuitiveness. """))

            if int(wisdom) in figures:
            figures.remove( wisdom)
            else:
            print "Don't try to cheat! Naughty! Everlasting curses upon thee!!"
            while 1<2:
            print "Cheater!"
            print ""


            print ""
            print ""
            print figures
            print ""
            print ""



            print "Then the last one will be your character's Charisma."
            print """Charisma is the measure of the character's combined physical attractiveness,
            persuasiveness, and personal magnetism. A generally non-beautiful character
            can have a very high charisma due to strong measures of
            the other two aspects of charisma."""
            charisma=figure s[0]
            del figures

            print ''
            print ''
            print ''
            print ''
            print ''
            print ''
            print ''
            print ''
            print ''
            print ''
            print ''
            print ''
            print ''
            print ''
            print ''
            print ''
            print ''
            print ''
            print ''
            print ''
            print ''
            print ''
            print ''
            print ''
            print ''


            print '....... Physical Traits .......'
            print 'strength = %s ' % strength
            print 'dexterity = %s ' % dexterity
            print 'constitution = %s ' % constitution
            print '....... Mental Traits .......'
            print 'intelligence = %s ' % intelligence
            print 'charisma = %s ' % charisma
            print 'wisdom = %s ' % wisdom
            print ''

            if strength in (8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18) and dexterity in (3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17) and constitution in (11, 12, 13, 14, 15, 16, 17, 18) and charisma in (8, 9, 10, 11, 12, 13, 14, 15, 16, 17):
            print 'You are eligible to be a dwarf.'

            if dexterity in (6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18) and constitution in (7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18) and intelligence in (8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18) and charisma in (8, 9, 10, 11, 12, 13, 14, 15, 16, 17):
            print 'You are eligible to be an elf.'

            if strength in (6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18) and constitution in (8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18) and intelligence in (6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18):
            print 'You are eligilbe to be a gnome.'

            if dexterity in (6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18) and constitution in (6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18) and intelligence in (4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18):
            print 'You are eligilbe to be a half-elf.'

            if strength in (7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18) and dexterity in (7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18) and constitution in (10, 11, 12, 13, 14, 15, 16, 17, 18) and intelligence in (6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18) and wisdom in (3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17):
            print 'You are eligilbe to be a halfling.'

            print 'You are eligible to be a human.'

            print ''

            race=raw_input( 'Which race do you want your character to be? ')

            if race is 'dwarf' or 'Dwarf':
            constitution==c onstitution+1
            charisma==chari sma-1

            if race is 'elf' or 'Elf':
            dexterity=dexte rity+1
            constitution=co nstitution-1

            if race is 'gnome' or 'Gnome':
            intelligence=in telligence+1
            wisdom=wisdom-1

            if race is 'halfling' or 'Halfling':
            dexterity=dexte rity+1
            strength=streng th-1

            print ''
            print ''
            print ''
            print ''
            print ''
            print ''
            print ''
            print ''
            print ''
            print ''
            print ''
            print ''
            print ''
            print ''
            print ''
            print ''
            print ''
            print ''
            print ''
            print ''
            print ''
            print ''
            print ''
            print ''
            print ''

            print "your character's sex is %s" % sex
            print "your character's race is %s" % race
            print ''
            print '....... Physical Traits .......'
            print 'strength = %s ' % strength
            print 'dexterity = %s ' % dexterity
            print 'constitution = %s ' % constitution
            print '....... Mental Traits .......'
            print 'intelligence = %s ' % intelligence
            print 'charisma = %s ' % charisma
            print 'wisdom = %s ' % wisdom
            print ''


            if strength in (9, 10, 11, 12, 13, 14, 15, 16, 17, 18):
            print 'you are eligible to be a warrior.'

            if intelligence in (9, 10, 11, 12, 13, 14, 15, 16, 17, 18):
            print 'you are eligilbe to be a mage.'

            if wisdom in (9, 10, 11, 12, 13, 14, 15, 16, 17, 18):
            print 'you are eligilbe to be a cleric.'

            if dexterity in (9, 10, 11, 12, 13, 14, 15, 16, 17, 18):
            print 'you are eligilbe to be a thief.'

            print ''

            class1=raw_inpu t('Which class do you want to be? ')

            print ''
            print ''
            print ''
            print ''
            print ''
            print ''
            print ''
            print ''
            print ''
            print ''
            print ''
            print ''
            print ''
            print ''
            print ''
            print ''
            print ''
            print ''
            print ''
            print ''
            print ''
            print ''
            print ''
            print '--------------------------------------'
            print "Your character's sex is: %s" % sex
            print "Your character's name is: %s" % name
            print "Your character's race is: %s" % race
            print "Your character's class is: %s" % class1
            print '--------------------------------------'
            print '....... Physical Traits .......'
            print 'strength = %s ' % strength
            print 'dexterity = %s ' % dexterity
            print 'constitution = %s ' % constitution
            print '....... Mental Traits .......'
            print 'intelligence = %s ' % intelligence
            print 'charisma = %s ' % charisma
            print 'wisdom = %s ' % wisdom
            print ''
            yes="yes"
            name2=raw_input ("Now that you know this, do you wish to change your character's name? yes / no. ")

            if name2==yes:
            name=raw_input( " What do you wish to name your character? ")
            else:
            print ''


            print ''
            print ''
            print ''
            print ''
            print ''
            print ''
            print ''
            print ''
            print ''
            print ''
            print ''
            print ''
            print ''
            print ''
            print ''
            print ''
            print ''
            print ''
            print ''
            print ''
            print ''


            Lawful="Lawful"
            Chaotic="Chaoti c"
            Neutral="Neutra l"
            Good="Good"
            Evil="Evil"
            lawful="lawful"
            chaotic="chaoti c"
            neutral="neutra l"
            good="good"
            evil="evil"

            print '.......... Alignments 1: Law and Chaos .............'
            print ''



            for n in range(1,50):
            aligninfo=raw_i nput("You may choose to be Lawful, Neutral or Chaotic. For more information, type in the alignment you want more information about. If you do not want any information and just want to get on with choosing, just press enter. ")


            if aligninfo==Lawf ul:
            print ""
            print 'Lawful characters tell the truth, keep their words, respect authority, honor tradition and judge those who fall short of their duties.'
            print ""
            print ""

            elif aligninfo==Chao tic:
            print ""
            print 'Chaotic characters follow their consciences, resent being told what to do, favor new ideas over tradition and do what they promise if they feel like it.'
            print ""
            print ""

            elif aligninfo==Neut ral:
            print ""
            print 'People who are neutral with respect to law and chaos have a normal respect for authority and feel neither a compulsion to obey nor to rebel, they are honest, but can be tempted into lying or decieving others.'
            print ""
            print ""

            elif aligninfo==lawf ul:
            print ""
            print 'Lawful characters tell the truth, keep their words, respect authority, honor tradition and judge those who fall short of their duties.'
            print ""
            print ""

            elif aligninfo==chao tic:
            print ""
            print 'Chaotic characters follow their consciences, resent being told what to do, favor new ideas over tradition and do what they promise if they feel like it.'
            print ""
            print ""

            elif aligninfo==neut ral:
            print ""
            print 'People who are neutral with respect to law and chaos have a normal respect for authority and feel neither a compulsion to obey nor to rebel, they are honest, but can be tempted into lying or decieving others.'
            print ""
            print ""


            else:
            print ""
            print ""
            break

            al1=raw_input(" Enter the alignment you have chosen. ")
            print ""
            print "Thank you! Moving on!"




            print ""
            print ""
            print ".......... Alignments 2: Good versus Evil .........."
            print ""




            for n in range(1,50):
            aligninfo=raw_i nput("You may choose to be either Good, Neutral or Evil. If you want some general info on the different alignments; type either Good, Neutral or Evil. If not, simply press enter. ")



            if aligninfo==Good :
            print ""
            print '"Good" implies altruism, respect for life, and a concern for the dignity of sentinent beings. Good characters make personal sacrifises to help others.'
            print ""
            print ""

            elif aligninfo==Neut ral:
            print ""
            print "People who are neutral with respect to good and evil have compunctions against killing the innocent but lack the commitment to make sacrifices to protect or help others. Neutral people are committed to others through personal relationships. A neutral person may sacrifice himself to protect his family or even his homeland, but he would not do so for strangers who are not related to him."
            print ""
            print ""

            elif aligninfo==Evil :
            print ""
            print '"Evil" implies hurting, oppressing and killing others. Some evil creatures simply have no compassion for others and would kill without qualms if doing so is convenient. Others actively pursue evil, killing for sport or out of duty to some evil deity or master'
            print ""
            print ""

            elif aligninfo==good :
            print ""
            print '"Good" implies altruism, respect for life, and a concern for the dignity of sentinent beings. Good characters make personal sacrifises to help others.'
            print ""
            print ""

            elif aligninfo==neut ral:
            print ""
            print "People who are neutral with respect to good and evil have compunctions against killing the innocent but lack the commitment to make sacrifices to protect or help others. Neutral people are committed to others through personal relationships. A neutral person may sacrifice himself to protect his family or even his homeland, but he would not do so for strangers who are not related to him."
            print ""
            print ""

            elif aligninfo==evil :
            print ""
            print '"Evil" implies hurting, oppressing and killing others. Some evil creatures simply have no compassion for others and would kill without qualms if doing so is convenient. Others actively pursue evil, killing for sport or out of duty to some evil deity or master'
            print ""
            print ""

            else:
            print ""
            print ""
            break

            al2=raw_input(" Type the alignment which you have chosen. ")
            print ""
            print ""
            print ""












            print ''
            print ''
            print ''
            print ''
            print 'Congratulation s, you have successfully created a dungeons and dragons character.'
            print '--------------------------------------'
            print "Your character's sex is: %s" % sex
            print "Your character's name is: %s" % name
            print "Your character's race is: %s" % race
            print "Your character's class is: %s" % class1
            print '--------------------------------------'
            print '....... Physical Traits .......'
            print 'strength = %s ' % strength
            print 'dexterity = %s ' % dexterity
            print 'constitution = %s ' % constitution
            print '....... Mental Traits .......'
            print 'intelligence = %s ' % intelligence
            print 'charisma = %s ' % charisma
            print 'wisdom = %s ' % wisdom
            print '--------------------------------------'
            print 'Alignment:' , al1 , al2
            print ''
            print ''
            print ''





            fn=r'c:\program filer\python script\characte rs.txt'
            outlist=[name,sex,race,c lass1,strength, dexterity,const itution,intelli gence,charisma, wisdom,(al1+" "+al2)]
            stuff=["Name","Sex","R ace","Class","S trength","Dexte rity","Constitu tion","Intellig ence","Charisma ","Wisdom","Ali gnment"]
            finallist=['%s=%s' % (stuff[n],outlist[n]) for n in range(len(stuff ))]
            f=open(fn,'a')
            f.write('\n'.jo in(finallist))
            f.close()


            fn=r'c:\program filer\python script\characte rs.txt'
            f=open(fn,'a')
            f.write('\n'.jo in('\n'))
            f.close()



            fn=r'c:\program filer\python script\characte rs.txt'
            f=open(fn,'a')
            f.write('\n'.jo in('\n'))
            f.close()


            fn=r'c:\program filer\python script\characte rs.txt'
            f=open(fn,'a')
            f.write('\n'.jo in('\n'))
            f.close()







            for n in range(20):
            if strength is n:
            strength=str(n)

            if dexterity is n:
            dexterity=str(n )

            if constitution is n:
            constitution=st r(n)

            if intelligence is n:
            intelligence=st r(n)

            if wisdom is n:
            wisdom=str(n)

            if charisma is n:
            charisma=str(n)








            fn=r'c:\program filer\python script\characte r-pro.txt'


            f=open(fn, 'a')
            f.write('\n'.jo in('\n'))
            f.close()

            f=open(fn, 'a')
            f.write("--------------------------------")
            f.close()

            f=open(fn, 'a')
            f.write('\n'.jo in('\n'))
            f.close()

            f=open(fn, 'a')
            f.write("This character's name is: ")
            f.close()


            f=open(fn, 'a')
            f.write(name)
            f.close()


            f=open(fn, 'a')
            f.write('\n'.jo in('\n'))
            f.close()


            f=open(fn, 'a')
            f.write("It is a: ")
            f.close()


            f=open(fn, 'a')
            f.write(race)
            f.close()


            f=open(fn, 'a')
            f.write('\n'.jo in('\n'))
            f.close()

            f=open(fn, 'a')
            f.write("It's sex is: ")
            f.close()


            f=open(fn, 'a')
            f.write(sex)
            f.close()


            f=open(fn, 'a')
            f.write('\n'.jo in('\n'))
            f.close()


            if sex=="female":


            f=open(fn, 'a')
            f.write("She is a: ")
            f.close()


            f=open(fn, 'a')
            f.write(class1)
            f.close()


            elif sex=="Female":


            f=open(fn, 'a')
            f.write("She is a: ")
            f.close()


            f=open(fn, 'a')
            f.write(class1)
            f.close()


            elif sex=="male":


            f=open(fn, 'a')
            f.write("He is a: ")
            f.close()


            f=open(fn, 'a')
            f.write(class1)
            f.close()


            elif sex=="Male":


            f=open(fn, 'a')
            f.write("He is a: ")
            f.close()


            f=open(fn, 'a')
            f.write(class1)
            f.close()


            f=open(fn, 'a')
            f.write('\n'.jo in('\n'))
            f.close()


            f=open(fn, 'a')
            f.write("--------------------------------")
            f.close()


            f=open(fn, 'a')
            f.write('\n'.jo in('\n'))
            f.close()


            f=open(fn, 'a')
            f.write("...... . Physical Traits .......")
            f.close()


            f=open(fn, 'a')
            f.write('\n'.jo in('\n'))
            f.close()


            f=open(fn, 'a')
            f.write("Streng th: ")
            f.close()


            f=open(fn, 'a')
            f.write(strengt h)
            f.close()


            f=open(fn, 'a')
            f.write('\n'.jo in('\n'))
            f.close()


            f=open(fn, 'a')
            f.write("Dexter ity: ")
            f.close()


            f=open(fn, 'a')
            f.write(dexteri ty)
            f.close()


            f=open(fn, 'a')
            f.write('\n'.jo in('\n'))
            f.close()


            f=open(fn, 'a')
            f.write("Consti tution: ")
            f.close()


            f=open(fn, 'a')
            f.write(constit ution)
            f.close()


            f=open(fn, 'a')
            f.write('\n'.jo in('\n'))
            f.close()


            f=open(fn, 'a')
            f.write("...... .. Mental Traits ........")
            f.close()


            f=open(fn, 'a')
            f.write('\n'.jo in('\n'))
            f.close()


            f=open(fn, 'a')
            f.write("Intell igence: ")
            f.close()


            f=open(fn, 'a')
            f.write(intelli gence)
            f.close()


            f=open(fn, 'a')
            f.write('\n'.jo in('\n'))
            f.close()


            f=open(fn, 'a')
            f.write("Charis ma: ")
            f.close()


            f=open(fn, 'a')
            f.write(charism a)
            f.close()


            f=open(fn, 'a')
            f.write('\n'.jo in('\n'))
            f.close()


            f=open(fn, 'a')
            f.write("Wisdom : ")
            f.close()


            f=open(fn, 'a')
            f.write(wisdom)
            f.close()


            f=open(fn, 'a')
            f.write('\n'.jo in('\n'))
            f.close()


            f=open(fn, 'a')
            f.write("--------------------------------")
            f.close()


            f=open(fn, 'a')
            f.write('\n'.jo in('\n'))
            f.close()


            f=open(fn, 'a')
            f.write("Alignm ent: ")
            f.close()


            f=open(fn, 'a')
            f.write(al1)
            f.close()


            f=open(fn, 'a')
            f.write(" ")
            f.close()


            f=open(fn, 'a')
            f.write(al2)
            f.close()


            f=open(fn, 'a')
            f.write('\n'.jo in('\n'))
            f.close()


            f=open(fn, 'a')
            f.write('\n'.jo in('\n'))
            f.close()


            f=open(fn, 'a')
            f.write('\n'.jo in('\n'))
            f.close()


            raw_input("You are finished! To quit this character-creator; press enter.")

            [/CODE]


            I'm sorry for the lack of comments. It is a dice-based game, and this is a program for creating characters. I do not think the rules need be explained. The problem is the lower half, which I expect is vastly useless, and can be written in much shorter ways...

            Comment

            • BurnTard
              New Member
              • May 2007
              • 52

              #7
              [CODE=python]'%s'='%s'[/CODE]


              ... is the only thing that I still don't understand. I was without internet for some time, and bored out of my mind I tried to force pyton into telling me what those things did... it wasn't all easy... was rather hard to get the exact __doc__ for write, since it just wrote to the file, instead of giving info... This is what I made when I gave up understanding " '%s'='%s' ":

              I'm posting the entire script, so it's rather a lot


              I'm sorry for the lack of comments. It is a dice-based game, and this is a program for creating characters. I do not think the rules need be explained. The problem is the lower half, which I expect is vastly useless, and can be written in much shorter ways...

              And of course it doesn't allow me... I'll post it as a .txt file in case anyone of you are interested...
              Attached Files

              Comment

              • ilikepython
                Recognized Expert Contributor
                • Feb 2007
                • 844

                #8
                Originally posted by BurnTard
                [CODE=python]'%s'='%s'[/CODE]


                ... is the only thing that I still don't understand. I was without internet for some time, and bored out of my mind I tried to force pyton into telling me what those things did... it wasn't all easy... was rather hard to get the exact __doc__ for write, since it just wrote to the file, instead of giving info... This is what I made when I gave up understanding " '%s'='%s' ":

                I'm posting the entire script, so it's rather a lot


                I'm sorry for the lack of comments. It is a dice-based game, and this is a program for creating characters. I do not think the rules need be explained. The problem is the lower half, which I expect is vastly useless, and can be written in much shorter ways...

                And of course it doesn't allow me... I'll post it as a .txt file in case anyone of you are interested...
                "%s = %s" just means string formatting. You need to specify some strings after the last quote using the percent:
                print "'%s' = '%s'" % ("strenght", "4")
                That would print:
                "strength = 4"

                Also, you have an open() and close() call for every call to write(). You only need to open and close the file once.

                Comment

                • BurnTard
                  New Member
                  • May 2007
                  • 52

                  #9
                  Originally posted by ilikepython

                  Also, you have an open() and close() call for every call to write(). You only need to open and close the file once.
                  Nope, I definitively do need to do it every bloody time, otherwise it claims that I haven't defined f... I know it should work without it, but it just doesn't...


                  *edit*= I found that by changing the f=open(fn,'a') into f=file(fn,'a'), I could write several times without having to close and redefine f...

                  Comment

                  • Smygis
                    New Member
                    • Jun 2007
                    • 126

                    #10
                    Originally posted by BurnTard
                    Nope, I definitively do need to do it every bloody time, otherwise it claims that I haven't defined f... I know it should work without it, but it just doesn't...


                    *edit*= I found that by changing the f=open(fn,'a') into f=file(fn,'a'), I could write several times without having to close and redefine f...
                    A lot of things:
                    [CODE=python]if race is 'dwarf' or 'Dwarf':[/CODE]
                    Is not what you want.
                    [CODE=python]if race in ('dwarf', 'Dwarf'):[/CODE]
                    Is what you want.

                    and if your realy clever, You use:

                    [CODE=python]if race.lower() == 'dwarf':[/CODE]
                    Then "dWaRF" would also be true.

                    And in the dwarf sction you got:
                    [CODE=python]constitution==c onstitution+1[/CODE]
                    Thats bad. As you can se you are using the == operator.

                    Preferably you shuld use the += operator.

                    [CODE=python]constitution += 1[/CODE]


                    And your fine:
                    [CODE=python]strength in (7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18)[/CODE]

                    Looks realy bad.
                    you can use the "in between" construction:

                    [CODE=python]if 7 <= strength <= 18:[/CODE]

                    and as you use:
                    [CODE=python]
                    print ''
                    print ''
                    print ''
                    print ''
                    print ''
                    print ''
                    print ''
                    print ''
                    print ''
                    print ''
                    print ''
                    print ''
                    print ''
                    print ''
                    print ''
                    print ''
                    print ''
                    print ''
                    print ''
                    print ''
                    print ''
                    print ''
                    print ''
                    [/CODE]
                    A lot.

                    It be good if you did something like:
                    [CODE=python]
                    newlines = "\n\n\n\n\n\n\n \n\n\n\n\n\n\n\ n\n\n\n\n"
                    # And then when you want a lot of newlines:
                    print newlines
                    [/CODE]

                    And the print statements always (unless you use ",") end with a linebreak.
                    so:
                    [CODE=python]
                    print ''
                    # and
                    print
                    [/CODE]
                    do the same thing.

                    And if you want to use:
                    [CODE=python]
                    while 1<2:
                    # a statement that is alwas true. Use:
                    while True:
                    [/CODE]

                    And you dont need:
                    [CODE=python]if int(wisdom) in figures:
                    #when its already an int. Do:
                    if wisdom in figures:
                    [/CODE]


                    Keep it up ;)
                    you can only get better.

                    Comment

                    • bvdet
                      Recognized Expert Specialist
                      • Oct 2006
                      • 2851

                      #11
                      You can also print multiple new lines this way:[code=Python]>>> print '\n'*8









                      >>> [/code]This works for any character or string.

                      Comment

                      • bvdet
                        Recognized Expert Specialist
                        • Oct 2006
                        • 2851

                        #12
                        Originally posted by BurnTard
                        Nope, I definitively do need to do it every bloody time, otherwise it claims that I haven't defined f... I know it should work without it, but it just doesn't...


                        *edit*= I found that by changing the f=open(fn,'a') into f=file(fn,'a'), I could write several times without having to close and redefine f...
                        Instead of doing this:[code=Python]fn=r'c:\program filer\python script\characte rs.txt'
                        outlist=[name,sex,race,c lass1,strength, dexterity,const itution,intelli gence,charisma, wisdom,(al1+" "+al2)]
                        stuff=["Name","Sex","R ace","Class","S trength","Dexte rity","Constitu tion","Intellig ence","Charisma ","Wisdom","Ali gnment"]
                        finallist=['%s=%s' % (stuff[n],outlist[n]) for n in range(len(stuff ))]

                        f=open(fn,'a')
                        f.write('\n'.jo in(finallist))
                        f.close()


                        fn=r'c:\program filer\python script\characte rs.txt'
                        f=open(fn,'a')
                        f.write('\n'.jo in('\n'))
                        f.close()[/code]You can do this:[code=Python]fn=r'c:\program filer\python script\characte rs.txt'
                        outlist=[name,sex,race,c lass1,strength, dexterity,const itution,intelli gence,charisma, wisdom,(al1+" "+al2)]
                        stuff=["Name","Sex","R ace","Class","S trength","Dexte rity","Constitu tion","Intellig ence","Charisma ","Wisdom","Ali gnment"]
                        finallist=['%s=%s' % (stuff[n],outlist[n]) for n in range(len(stuff ))]

                        f = open(fn,'a') # open a file in append mode, create the file if it does not exist
                        f.write('\n'.jo in(finallist))
                        f.write('\n')
                        ...do other stuff...

                        f.write('\nsome string\n')
                        f.writelines([s1, s1,s3]) # this writes a list of strings
                        f.close()
                        [/code]There is no difference in the use of open() and file(). From Python docs:
                        The file() constructor is new in Python 2.2. The previous spelling, open(), is retained for compatibility, and is an alias for file().

                        Comment

                        • BurnTard
                          New Member
                          • May 2007
                          • 52

                          #13
                          Originally posted by bvdet
                          Instead of doing this:[code=Python]fn=r'c:\program filer\python script\characte rs.txt'
                          outlist=[name,sex,race,c lass1,strength, dexterity,const itution,intelli gence,charisma, wisdom,(al1+" "+al2)]
                          stuff=["Name","Sex","R ace","Class","S trength","Dexte rity","Constitu tion","Intellig ence","Charisma ","Wisdom","Ali gnment"]
                          finallist=['%s=%s' % (stuff[n],outlist[n]) for n in range(len(stuff ))]

                          f=open(fn,'a')
                          f.write('\n'.jo in(finallist))
                          f.close()


                          fn=r'c:\program filer\python script\characte rs.txt'
                          f=open(fn,'a')
                          f.write('\n'.jo in('\n'))
                          f.close()[/code]You can do this:[code=Python]fn=r'c:\program filer\python script\characte rs.txt'
                          outlist=[name,sex,race,c lass1,strength, dexterity,const itution,intelli gence,charisma, wisdom,(al1+" "+al2)]
                          stuff=["Name","Sex","R ace","Class","S trength","Dexte rity","Constitu tion","Intellig ence","Charisma ","Wisdom","Ali gnment"]
                          finallist=['%s=%s' % (stuff[n],outlist[n]) for n in range(len(stuff ))]

                          f = open(fn,'a') # open a file in append mode, create the file if it does not exist
                          f.write('\n'.jo in(finallist))
                          f.write('\n')
                          ...do other stuff...

                          f.write('\nsome string\n')
                          f.writelines([s1, s1,s3]) # this writes a list of strings
                          f.close()
                          [/code]There is no difference in the use of open() and file(). From Python docs:
                          The file() constructor is new in Python 2.2. The previous spelling, open(), is retained for compatibility, and is an alias for file().

                          Well obviously there is some difference, for when I did the
                          [code=python]
                          "f = open(fn,'a') # open a file in append mode, create the file if it does not exist
                          f.write('\n'.jo in(finallist))
                          f.write('\n')
                          ...do other stuff...

                          f.write('\nsome string\n')"

                          [/code]
                          thing, it gave me the error message "Line 'something', f.write(Some stuff)
                          f not specified

                          but when I specified f at every line, like this:

                          [code=python]

                          f=open(fn, 'a')
                          f.write(some stuff)
                          f.close()

                          f=open(fn, 'a')
                          f.write(some other stuff)
                          f.close()

                          [/code]

                          It worked perfectly, it was just annoying. When I spedified f as:

                          [Code=python]
                          f=file(fn, 'a')
                          [/code]

                          It didn't have to be specified and closed every time... Maybe my version is just buggy and glitchy, but whatever the reason, that is the way it is for me.

                          Comment

                          • BurnTard
                            New Member
                            • May 2007
                            • 52

                            #14
                            Originally posted by Smygis
                            A lot of things:
                            Code:
                            if race is 'dwarf' or 'Dwarf':
                            Is not what you want.
                            Code:
                            if race in ('dwarf', 'Dwarf'):
                            Is what you want.

                            and if your realy clever, You use:

                            Code:
                            if race.lower() == 'dwarf':
                            Then "dWaRF" would also be true.

                            And in the dwarf sction you got:
                            Code:
                            constitution==constitution+1
                            Thats bad. As you can se you are using the == operator.

                            Preferably you shuld use the += operator.

                            Code:
                            constitution += 1

                            And your fine:
                            Code:
                            strength in (7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18)
                            Looks realy bad.
                            you can use the "in between" construction:

                            Code:
                            if 7 <= strength <= 18:
                            and as you use:
                            Code:
                            print ''
                            print ''
                            print ''
                            print ''
                            print ''
                            print ''
                            print ''
                            print ''
                            print ''
                            print ''
                            print ''
                            print ''
                            print ''
                            print ''
                            print ''
                            print ''
                            print ''
                            print ''
                            print ''
                            print ''
                            print ''
                            print ''
                            print ''
                            A lot.

                            It be good if you did something like:
                            Code:
                            newlines = "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n"
                            # And then when you want a lot of newlines:
                            print newlines
                            And the print statements always (unless you use ",") end with a linebreak.
                            so:
                            Code:
                            print ''
                            # and
                            print
                            do the same thing.

                            And if you want to use:
                            Code:
                            while 1<2:
                            # a statement that is alwas true. Use:
                            while True:
                            And you dont need:
                            Code:
                            if int(wisdom) in figures:
                            #when its already an int. Do:
                            if wisdom in figures:

                            Keep it up ;)
                            you can only get better.
                            Basically all of that was not made by me, and the int(wisdom) was done just because I knew it would work, and was tired of testing the entire script for every addition. The newlines="\n\n\ n\n\n\n\n" was quite smart though, I shall have to remember that.

                            As for the operator +=... I've never seen it before, neither the race.lower()...

                            But thanks! You should talk to some admin or whatever and make them change the "newbie" there... It really doesn't suit you :P

                            Comment

                            • BurnTard
                              New Member
                              • May 2007
                              • 52

                              #15
                              Originally posted by bvdet
                              You can also print multiple new lines this way:[code=Python]>>> print '\n'*8









                              >>> [/code]This works for any character or string.
                              Thanks, I was kinda wondering about that... never "dared" try it tho :P

                              Comment

                              Working...