Writing things to <file>.<ext>

  • (2 Pages)
  • +
  • 1
  • 2

17 Replies - 1045 Views - Last Post: 11 July 2012 - 03:58 PM Rate Topic: -----

#1 BloodyInari  Icon User is offline

  • D.I.C Head

Reputation: 6
  • View blog
  • Posts: 106
  • Joined: 16-November 09

Writing things to <file>.<ext>

Posted 02 July 2012 - 04:31 PM

So, I'm writing out a little script that basically asks if a user wants to store a username, which then specifies in a file."file_type" and goes on to ask how many usernames, which can be specified by the user, blah, blah, blah, looping until you've met the number specified. Runs smoothly except where it encounters an error in "writing" the output from the array the name is stored and called from. The shell module outputs a type error like so, "unsupported operand type(s) for +: 'NoneType' and 'str'". Any ideas on how to resolve?

                        num = input("How many usernames do you have? ")
                        uName = []
                        
                        for i in range(num):
                                first = raw_input("\nFirst Name: ")
                                last = raw_input("\nLast Name: ")

                                uName[i] = uName.append((first[0] + last[:(len(last)/2)]))

                                outfile = open(outfileName, "w")

                                outfile.write(uName[i] + "\n")



Whole snippet of the code is attached for context.

Attached File(s)



Is This A Good Question/Topic? 0
  • +

Replies To: Writing things to <file>.<ext>

#2 atraub  Icon User is offline

  • Pythoneer
  • member icon

Reputation: 759
  • View blog
  • Posts: 2,010
  • Joined: 23-December 08

Re: Writing things to <file>.<ext>

Posted 02 July 2012 - 08:42 PM

I'm going to post the full code, it'll be easier for all of us to help this way:
import string
def main():
        again = raw_input("\nDo you want to store usernames? (y/n) ")

        #checks if either of two possible inputs
        if again != "n" and again != "y":
                print "\nInvalid input"
                return main()
        
        #secondary conditional statement, starts loop to store data   
        elif again != "n":
                
                #asks where to store username as a file
                outfileName = raw_input("\nWhat file should the usernames go in? ")

                #conditional loop, asks for string input to store as data in another file
                while again != "n":
                        
                        num = input("How many usernames do you have? ")
                        uName = []
                        
                        for i in range(num):
                        
                                #asks for input strings to generate a username
                                first = raw_input("\nFirst Name: ")
                                last = raw_input("\nLast Name: ")

                                #generate username from input strings
                                uName[i] = uName.append((first[0] + last[:(len(last)/2)]))

                                #create and open output file
                                outfile = open(outfileName, "w")

                                #write it to the output file
                                outfile.write(uName[i] + "\n")

                        #conditional input
                        again = raw_input("\nDo you want to add more? (y/n) ")

                        #checks for exit based upon prior input
                        if again == "n":
                                print "\nStored. Exiting program."

                                #close file
                                outfile.close()
                                return

        #tertiary conditional loop, you do nothing                       
        elif again == "n":
                print "Nothing stored."
        
main()



Was This Post Helpful? 0
  • +
  • -

#3 Dogstopper  Icon User is offline

  • The Ninjaducky
  • member icon



Reputation: 2872
  • View blog
  • Posts: 11,032
  • Joined: 15-July 08

Re: Writing things to <file>.<ext>

Posted 02 July 2012 - 08:56 PM

You have:
uName[i] = uName.append(...)



append() does not return any value because it operates on the list, not returns an item from it. What you should do is instead of writing to the file for every user name (and opening), you should instead do that in another loop.
Was This Post Helpful? 2
  • +
  • -

#4 sepp2k  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 2117
  • View blog
  • Posts: 3,242
  • Joined: 21-June 11

Re: Writing things to <file>.<ext>

Posted 03 July 2012 - 02:49 AM

View PostDogstopper, on 03 July 2012 - 05:56 AM, said:

What you should do is instead of writing to the file for every user name (and opening), you should instead do that in another loop.


I don't think a second loop is really necessary for that. He can just do:

name = first[0] + last[:(len(last)/2)]
uName.append(name)
outfile.write(name + "\n")



He definitely needs to open outfile before the loop though - not at each iteration.

Edit: Actually, now that I looked at the entire code, it doesn't seem like he actually uses uName anywhere, so he should just get rid of it altogether and just do:

name = first[0] + last[:(len(last)/2)]
outfile.write(name + "\n")


This post has been edited by sepp2k: 03 July 2012 - 02:51 AM

Was This Post Helpful? 2
  • +
  • -

#5 atraub  Icon User is offline

  • Pythoneer
  • member icon

Reputation: 759
  • View blog
  • Posts: 2,010
  • Joined: 23-December 08

Re: Writing things to <file>.<ext>

Posted 03 July 2012 - 07:51 AM

Haha I meant to actually try to answer this one, but some things got in the way lol

This post has been edited by atraub: 03 July 2012 - 07:53 AM

Was This Post Helpful? 0
  • +
  • -

#6 BloodyInari  Icon User is offline

  • D.I.C Head

Reputation: 6
  • View blog
  • Posts: 106
  • Joined: 16-November 09

Re: Writing things to <file>.<ext>

Posted 03 July 2012 - 02:02 PM

View PostDogstopper, on 02 July 2012 - 10:56 PM, said:

You have:
uName[i] = uName.append(...)



append() does not return any value because it operates on the list, not returns an item from it. What you should do is instead of writing to the file for every user name (and opening), you should instead do that in another loop.



View Postsepp2k, on 03 July 2012 - 04:49 AM, said:

View PostDogstopper, on 03 July 2012 - 05:56 AM, said:

What you should do is instead of writing to the file for every user name (and opening), you should instead do that in another loop.

He definitely needs to open outfile before the loop though - not at each iteration.


Dogstopper, thanks for that bit, I was able to get the usernames to store to the array properly by doing this
uName.append((first[0] + last[:(len(last)/2)]))


rather than having it set up like before, which like you said returns a null value.

sepp2k, I'm playing with what you said concerning the location of opening/writing to the file, as the problem I had before is that it would only write one username into the file regardless of the number of actual usernames I tried to store. I'll update with more as I have just read the topic and its contents therein.
Was This Post Helpful? 0
  • +
  • -

#7 sepp2k  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 2117
  • View blog
  • Posts: 3,242
  • Joined: 21-June 11

Re: Writing things to <file>.<ext>

Posted 03 July 2012 - 02:07 PM

View PostBloodyInari, on 03 July 2012 - 11:02 PM, said:

sepp2k, I'm playing with what you said concerning the location of opening/writing to the file, as the problem I had before is that it would only write one username into the file regardless of the number of actual usernames I tried to store.


Yes, that's what happens if you open the file on each iteration of the loop because opening the file in write mode will erase the file's previous contents. So each time you write an entry to the file, the previous entry is overwritten. So only the last entry will be in the file at the end. If you open the file once before the loop and close it after the loop, everything should work fine.
Was This Post Helpful? 0
  • +
  • -

#8 BloodyInari  Icon User is offline

  • D.I.C Head

Reputation: 6
  • View blog
  • Posts: 106
  • Joined: 16-November 09

Re: Writing things to <file>.<ext>

Posted 03 July 2012 - 02:08 PM

Ok, it works perfectly, like so.
import string
def main():
        again = raw_input("\nDo you want to store usernames? (y/n) ")

        #checks if either of two possible inputs
        if again != "n" and again != "y":
                print "\nInvalid input"
                return main()
        
        #secondary conditional statement, starts loop to store data   
        elif again != "n":
                
                #asks where to store username as a file
                outfileName = raw_input("\nWhat file should the usernames go in? ")

                #conditional loop, asks for string input to store as data in another file
                while again != "n":
                        
                        num = input("How many usernames do you have? ")
                        uName = []

                        #create and open output file
                        outfile = open(outfileName, "w")
                                
                        for i in range(num):
                        
                                #asks for input strings to generate a username
                                first = raw_input("\nFirst Name: ")
                                last = raw_input("\nLast Name: ")

                                #generate & store username from input strings
                                uName.append((first[0] + last[:(len(last)/2)]))

                                #write it to the output file
                                outfile.write(uName[i] + "\n")
                        
                        #conditional input
                        again = raw_input("\nDo you want to add more? (y/n) ")

                        #checks for exit based upon prior input
                        if again == "n":
                                print "\nStored. Exiting program."

                                #close file
                                outfile.close()
                                return

        #tertiary conditional loop, you do nothing                       
        elif again == "n":
                print "Nothing stored."
        
main()



so if I run the program and paste this as input...
Do you want to store usernames? (y/n) y

What file should the usernames go in? username.txt
How many usernames do you have? 3

First Name: Falco

Last Name: Lombardi

First Name: General

Last Name: Pepper

First Name: Fox

Last Name: McCloud

Do you want to add more? (y/n) n

Stored. Exiting program.



the output is....
FLomb
GPep
FMcC



Excellent!
Was This Post Helpful? 0
  • +
  • -

#9 sepp2k  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 2117
  • View blog
  • Posts: 3,242
  • Joined: 21-June 11

Re: Writing things to <file>.<ext>

Posted 03 July 2012 - 02:11 PM

I just want to point out again that there's no reason to store the current line in an array before you write it to the file if you never use the array otherwise.
Was This Post Helpful? 0
  • +
  • -

#10 BloodyInari  Icon User is offline

  • D.I.C Head

Reputation: 6
  • View blog
  • Posts: 106
  • Joined: 16-November 09

Re: Writing things to <file>.<ext>

Posted 03 July 2012 - 02:57 PM

Actually, the array is necessary for when you enter through the conditional if statement for adding more names. I've made some edits since my last post as it is faulty as such, but the array eventually gets called to write all elements of the array to the file.
Was This Post Helpful? 0
  • +
  • -

#11 Dogstopper  Icon User is offline

  • The Ninjaducky
  • member icon



Reputation: 2872
  • View blog
  • Posts: 11,032
  • Joined: 15-July 08

Re: Writing things to <file>.<ext>

Posted 03 July 2012 - 03:41 PM

Yeah, sepp2k, I assumed he needed to store them for something else along with the side effect of printing it out. I've seen it in many introductory classes to "use an array to store and print information" even when unnecessary. But yeah, not needed.
Was This Post Helpful? 0
  • +
  • -

#12 k3y  Icon User is offline

  • D.I.C Head

Reputation: 36
  • View blog
  • Posts: 205
  • Joined: 25-February 12

Re: Writing things to <file>.<ext>

Posted 11 July 2012 - 03:14 PM

I was messing with the code a tad:
#!/usr/bin/python3
def main():
    check = input('\nDo you want to store usernames? (y/n)')

    if check != "n" and check != "y":
        print ('\nInvalid Input')
        return main()
    
    elif check != 'n' or 'N':
        output = input('\nWhat should the name of the file be, containing the username(s) be? ')
        if output == ' ' or '':
            main()
        else:
            while check != 'N' or 'n':
                uName = []
                number = int(input('How many usernames do you have?'))
                for x in range(number):
                    first = input('\n First Name: ')
                    last = input('\n Last Name: ')
                    try:
                        uName.append((first[0] + last[:(len(last)/2)]))
                        output.write(uName[x] + '\n')
                    except ValueError:
                        print ('Something went wrong')
                    finally:
                        output.close()
                again = input('\nDo you want to add more? (y,n) ')
                if again == 'n' or 'N':
                    print ('\nStored. Exiting program')
                    output.close()
                    return

    
    elif again == 'n' or 'N':
        print('Nothing Stored.')
main()



However I recieve this error:
Traceback (most recent call last):
  File "/home/k3y/Python/Look2.py", line 36, in <module>
    main()
  File "/home/k3y/Python/Look2.py", line 26, in main
    output.close()
AttributeError: 'str' object has no attribute 'close'



Could anyone please assist me in this code. I would deeply appreciate an explanation as well
Was This Post Helpful? 0
  • +
  • -

#13 Dogstopper  Icon User is offline

  • The Ninjaducky
  • member icon



Reputation: 2872
  • View blog
  • Posts: 11,032
  • Joined: 15-July 08

Re: Writing things to <file>.<ext>

Posted 11 July 2012 - 03:21 PM

output is a string type, not a file type. You have to actually open a file using the built in function open(). Google has thousands of examples of this.
Was This Post Helpful? 0
  • +
  • -

#14 sepp2k  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 2117
  • View blog
  • Posts: 3,242
  • Joined: 21-June 11

Re: Writing things to <file>.<ext>

Posted 11 July 2012 - 03:22 PM

In your code output is a string containing the name of the file you want to write to. You're treating that string as if it was itself a file object (you're calling .write and .close on it - methods that don't exist on strings), so you get an error.

You should open the file with open and then use the file handle returned by open - just as the OP does in his code.

PS: Recursing is not a very good way to handle invalid input. This would more cleanly be handled using a loop. (This applies to the OP's code as well).
Was This Post Helpful? 1
  • +
  • -

#15 k3y  Icon User is offline

  • D.I.C Head

Reputation: 36
  • View blog
  • Posts: 205
  • Joined: 25-February 12

Re: Writing things to <file>.<ext>

Posted 11 July 2012 - 03:27 PM

View PostDogstopper, on 11 July 2012 - 05:21 PM, said:

output is a string type, not a file type. You have to actually open a file using the built in function open(). Google has thousands of examples of this.


Yeah well; I looked at examples but didn't understand it. Thats why I asked for help
Was This Post Helpful? 0
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2