On Fri, Dec 16, 2011 at 11:49 PM, ADRIAN KELLY <kellyadr...@hotmail.com> wrote: > thanks dave, > just tried writing to file for the first time > > def main(): > outfile.write('Hello this is a test') > outfile.close() > main() > > error, globalname outfile is not defined, do i need to import function to > get this working? >
A lot of stuff is missing here. let's get back to basics. What is outfile? It's a variable. So, where does it come from? well, right now, you just sort of magically conjure it up out of nowhere, which is why python is complaining ("not defined" is the python telling you "you never told me what this thing is"). So, we want the variable outfile to point to a file object. Making a file object is very simple, just call the open() function. You don't have to import open(), it's a builtin, which means it's always available to you: outfile = open('file_name.txt', 'w') open takes two arguments. The first one is the filename, the second is the mode in which the file is to be opened. Basically, 'r' is for reading, 'w' for writing (this mode will delete existing data in the file, if any), and 'a' is appending. You can add a 'b' for opening in binary mode, and a '+' for opening the file for updating. Now we have a file object, and we can use the write() method on it as you have done above (make sure not to forget close(), it's good practice). That should get you started. There's a good bit of theory behind saving passwords securely (you don't usually want everyone to be able to open the file and read the passwords, basically), but I won't get into that right now. If you're ready for that, you might want to check out hashlib _______________________________________________ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor