Click to See Complete Forum and Search --> : A little help with my Python?? =)


Elijah
11-30-2003, 11:19 AM
It looks like simple one actually but since this is my first try in using Python I encountered this problem that's been keeping me stuck for hours now:


This is my simple code that writes to a file:
#!/usr/bin/python
uid = raw_input("Please enter your userID: ")
f = open("file.txt","w")
f.write("\nYour userID is %s") % uid

This is the error:
elijah@Valhalla:~/files/docs/academe/zopedev$ ./test2.py
Please enter your userID: eoa-100234
Traceback (most recent call last):
File "./test2.py", line 5, in ?
f.write("\nYour userID is %s") % uid
TypeError: unsupported operand type(s) for %: 'NoneType' and 'str'
:confused:

cfaun5
11-30-2003, 05:28 PM
Try:

f.write("\nYour userID is " + uid)

Elijah
11-30-2003, 05:50 PM
Cool it works =)

er, but suppose I add more variables to write:

f.write("\nYour userID is %s And your username is %s") % (uid,uname) ?

may I ask what book you're using? I can't seem to find much info on mine =)

bwkaz
11-30-2003, 06:35 PM
Going off cfaun's post, I'd say to do something like:

f.write("nYour userID is " + uid + " And your username is " + uname) but I don't use Python all that often.

I do know that the Python write() function only takes one argument, so you can't do like C's printf() family and have (any kind of) substitution going on. You can build a string, though, like the previous example. There may be something closer to printf() for streams, though; check http://doc.python.org if you haven't already.

Elijah
11-30-2003, 06:53 PM
It Works! :)

Thanks very much for the info bwkaz, and the link too =)

gotenks2
12-06-2003, 12:45 PM
Originally posted by Elijah
It looks like simple one actually but since this is my first try in using Python I encountered this problem that's been keeping me stuck for hours now:


This is my simple code that writes to a file:
#!/usr/bin/python
uid = raw_input("Please enter your userID: ")
f = open("file.txt","w")
f.write("\nYour userID is %s") % uid


Actually, to clarify you can do substitution in a
write. You just need to move your % inside
the write call as the string will be created before
the call to write is made.

So you can do something like this and it will work
just fine.


uid = raw_input("Please enter your UID: ")
f = file("file.txt", "w")
f.write("\nYour userID is %s" % (uid,))
f.close()


A few things to note. the open builtin is
deprecated and is currently just an alias for
file. Also, when you do substitution like
that it expects a tuple. Hence the (uid,) instead
of just uid. If any of this is clear as mud
let me know and I will try to explain a bit more.

:)
gotenks2