One mans freedom fighter, another's terrorist.
Friday, November 21, 2008
Navigation
Donate
Has this website helped you?
px
If so, please donate a little to help out with hosting costs.
Members Online
Total Online: 59
Web Spiders: 7
Guests Online: 45
Members Online: 14

Registered Members: 36827
Newest Member: Tecknoblade
Most Users online: 523
Latest Articles

Python lesson 4: File Handling


advertisement



website security Dealing with files



Python lesson 4: File Handling

Ok guys! Back into it.
This article is a follow on from [url=http://www.hellboundhackers.org/articles/698-Python-lesson-3:-(More)-Data-Structures.html]Lesson 3[/url]. If you're only here to learn how to play with files it'll all make sense, but the project at the bottom of the article is based heavily upon the last one.

Files:
When you open a file it attributes a "File-Like Object" to your variable. There are other things that have this property, some kinds of sockets, assorted other objects. It's also a common standard for writing your own objects.

So on with it.
To start you need to create your object.
myFile = open(path, mode)

path is rather self-explanatory. It follows all rules for the platform you're on. If you want to write multi-platform code that uses files across multiple directories, you'll need to tune in to my article on the os module, or do some research on http://www.python.org/doc/. Otherwise just use files in the same directory.

mode determines the way in which it opens the file. if left blank it defaults to read, which puts the iterator at the start of the file. The other modes are r, w, and a. These are not variables they are values, and so must be used in quotes.

so:
'r' : Puts the iterator at the start of the file, that is if you try to read teh next line you will get the first. Will throw an error if the file you have tried to open doesn't exist.
'w' : Opens the file for writing. If the file already exists, it doesn't now. Overwrites existing contents. Throws errors if you try to read from it.
'a' : Opens the file into a writable state. But leaves all existing contents. Puts the iterator at the end, so writing to it is possible. If the file doesn't exist it creates it.

Now the methods that apply TO file like objects.

Again, this is taken from http://docs.python.org/lib/bltin-file-objects.html

close() : I can't state this clearly enough. You NEED to have this in your programs, and implemented in such a way that it WILL run. In most cases if the program crashes, the OS can work itself out, but it's stupedously bad form to leave it up to the OS.

read(x) : Read x bytes from the file, including newline chars. You can leave x out, and it will return the entire contents of the file as a string.

readline() : Return the current line that is pointed to by the iterator.

write(data) : When the object is open for writing, appends the data to the end of the file. You'll need to put in your own endlines. \r, \n, or \n\r depending on OS. Python supports 'em all, so it's just a matter of how they'll show up in text editors.

newlines : This is a value, not a method, but appears when --with-universal-newlines is used to build Python, (don't worry! that's the default). the newlines value has either a single value, or a list of values representing all the newline characters it has seen in that file. It can be an excellent time and effort saver, rather than importing os for endlines.

Ok! Today's project. I'll be building on the phonebook from last time, adding two new options, Write to file, and Read from file. If you were very quick you may have noticed that the code from lesson 3 had a typo, it had "Type a number (1-7):" as the prompt, I was planning to put that in.
I won't add comments for the code that is identical to last time.


#!/usr/lib/python
def print_menu():
[tab]print '1. Print Phone Numbers'
[tab]print '2. Add a Phone Number'
[tab]print '3. Remove a Phone Number'
[tab]print '4. Lookup a Phone Number'
[tab]print '5. Write Phone Book to File' ##two new entries!
[tab]print '6. Read Phone Book From File'
[tab]print '7. Quit'
numbers = {}
menu_choice = 0
print_menu()
while menu_choice != 7:
[tab]menu_choice = input("Type a number (1-7):")
[tab]if menu_choice == 1:
[tab][tab]print "Telephone Numbers:"
[tab][tab]for x in numbers.keys():
[tab][tab][tab]print "Name: ",x," \tNumber: ",numbers[x],
[tab][tab]print
[tab]elif menu_choice == 2:
[tab][tab]print "Add name and number"
[tab][tab]name = raw_input("Name:")
[tab][tab]phone = raw_input("Number:")
[tab][tab]numbers[name] = phone
[tab]elif menu_choice == 3:
[tab][tab]print "Remove Name and Number"
[tab][tab]name = raw_input("Name:")
[tab][tab]if numbers.has_key(name):
[tab][tab][tab]del numbers[name]
[tab][tab]else:
[tab][tab][tab]print name, "was not found"
[tab]elif menu_choice == 4:
[tab][tab]print "Lookup Number"
[tab][tab]name = raw_input("Name:")
[tab][tab]if numbers.has_key(name):
[tab][tab][tab]print "The Number is",numbers[name]
[tab][tab]else:
[tab][tab][tab]print name,"was not found"
[tab]elif menu_choice == 5:
[tab][tab]phone_book = open('phone_book.txt', 'w') ## open the phone book to write. it may be an existing one, and we don't want to add a nearly identical entry to the end of an old one
[tab][tab]print "Write Phone Book to File"
[tab][tab]phone_book.write("Name: \t Number: \n") ## add an entry to it so if someone opens it it's readable
[tab][tab]for x in numbers.keys(): ## for each name in the book
[tab][tab][tab]#string = "Name: ",x," \tNumber: ",numbers[x] ## this is a comment by me. it's so i can remember what i'm writing to the files
[tab][tab][tab]phone_book.write(x) ## you can write over as many statements as you like.
[tab][tab][tab]phone_book.write(" ") ## so this is a much more orderly way of doing it
[tab][tab][tab]phone_book.write(numbers[x].replace(" ", "_") ## change spaces to _'s for storage
[tab][tab][tab]phone_book.write("\n")
[tab][tab]phone_book.close() ## always close your damn files!
[tab]elif menu_choice == 6:
[tab][tab]try: ## try except clause. Will be covered soon in a error handling article
[tab][tab][tab]print "Read Phone Book From File:"
[tab][tab][tab]phone_book = open('phone_book.txt', 'r') ## opening it with mode read
[tab][tab][tab]if phone_book != "": ## if the file is not empty. This is the statement that will throw the error if it does
[tab][tab][tab][tab]list = phone_book.readline() ## this is actually just to remove the index line we added earlier
[tab][tab][tab][tab]for line in phone_book:
[tab][tab][tab][tab][tab]myList = line.split(" ") ## seperate it into a list with 2 entries
[tab][tab][tab][tab][tab]numbers[myList[0]] = myList[1].replace("_", " ") ## rewrite it into the list with spaces instead of underscores
[tab][tab][tab][tab]phone_book.close()
[tab][tab]except:
[tab][tab] print "Phone book file does not exist!" ## Yell at the user for a bits
[tab]elif menu_choice != 7:
[tab][tab]print_menu()
Guest
Username

Password

Remember Me


Bookmark This Page
Affiliates
Adverts

 


By using, viewing or obtaining any information contained on this site, you agree to the disclaimer.

© HellBound Hackers 2007- 2008. Since 3rd December 2004.