?? node17.html
字號:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<!-- saved from url=(0062)http://www.honors.montana.edu/~jjc/easytut/easytut/node17.html -->
<!--Converted with LaTeX2HTML 99.2beta6 (1.42)original version by: Nikos Drakos, CBLU, University of Leeds* revised and updated by: Marcus Hennecke, Ross Moore, Herb Swan* with significant contributions from: Jens Lippmann, Marek Rouchal, Martin Wilck and others --><HTML><HEAD><TITLE>File IO</TITLE>
<META content="File IO" name=description>
<META content=easytut name=keywords>
<META content=document name=resource-type>
<META content=global name=distribution>
<META content="text/html; charset=iso-8859-1" http-equiv=Content-Type>
<META content="MSHTML 5.00.2614.3500" name=GENERATOR>
<META content=text/css http-equiv=Content-Style-Type><LINK
href="node17_files/easytut.css" rel=STYLESHEET><LINK href="node18.html"
rel=next><LINK href="node16.html" rel=previous><LINK href="easytut.html"
rel=up><LINK href="node18.html" rel=next></HEAD>
<BODY><!--Navigation Panel--><A
href="http://www.honors.montana.edu/~jjc/easytut/easytut/node18.html"
name=tex2html368><IMG align=bottom alt=next border=0 height=24
src="node17_files/next.png" width=37></A> <A
href="http://www.honors.montana.edu/~jjc/easytut/easytut/easytut.html"
name=tex2html364><IMG align=bottom alt=up border=0 height=24
src="node17_files/up.png" width=26></A> <A
href="http://www.honors.montana.edu/~jjc/easytut/easytut/node16.html"
name=tex2html358><IMG align=bottom alt=previous border=0 height=24
src="node17_files/prev.png" width=63></A> <A
href="http://www.honors.montana.edu/~jjc/easytut/easytut/node2.html"
name=tex2html366><IMG align=bottom alt=contents border=0 height=24
src="node17_files/contents.png" width=65></A> <BR><B>Next:</B> <A
href="http://www.honors.montana.edu/~jjc/easytut/easytut/node18.html"
name=tex2html369>Dealing with the imperfect</A> <B>Up:</B> <A
href="http://www.honors.montana.edu/~jjc/easytut/easytut/easytut.html"
name=tex2html365>Non-Programmers Tutorial For Python</A> <B>Previous:</B> <A
href="http://www.honors.montana.edu/~jjc/easytut/easytut/node16.html"
name=tex2html359>Revenge of the Strings</A> <B><A
href="http://www.honors.montana.edu/~jjc/easytut/easytut/node2.html"
name=tex2html367>Contents</A></B> <BR><BR><!--End of Navigation Panel--><!--Table of Child-Links--><A
name=CHILD_LINKS><STRONG>Subsections</STRONG></A>
<UL>
<LI><A
href="http://www.honors.montana.edu/~jjc/easytut/easytut/node17.html#SECTION001710000000000000000"
name=tex2html370>Exercises</A> </LI></UL><!--End of Table of Child-Links-->
<HR>
<H1><A name=SECTION001700000000000000000>File IO</A> </H1>Here is a simple
example of file IO: <PRE>#Write a file
out_file = open("test.txt","w")
out_file.write("This Text is going to out file\nLook at it and see\n")
out_file.close()
#Read a file
in_file = open("test.txt","r")
text = in_file.read()
in_file.close()
print text,
</PRE>The output and the contents of the file test.txt are: <PRE>This Text is going to out file
Look at it and see
</PRE>Notice that it wrote a file called test.txt in the directory that you ran
the program from. The <CODE>\n</CODE> in the string tells Python to put a
<B>n</B>ewline where it is.
<P>A overview of file IO is:
<OL>
<LI>Get a file object with the <CODE>open</CODE> function.
<LI>Read or write to the file object (depending on how it was opened)
<LI>Close it </LI></OL>
<P>The first step is to get a file object. The way to do this is to use the
<CODE>open</CODE> function. The format is <CODE>file_object =
open(filename,mode)</CODE> where <CODE>file_object</CODE> is the variable to put
the file object, <CODE>filename</CODE> is a string with the filename, and
<CODE>mode</CODE> is either <CODE>"r"</CODE> to <B>r</B>ead a file or
<CODE>"w"</CODE> to <B>w</B>rite a file. Next the file objects functions can be
called. The two most common functions are <CODE>read</CODE> and
<CODE>write</CODE>. The <CODE>write</CODE> function adds a string to the end of
the file. The <CODE>read</CODE> function reads the next thing in the file and
returns it as a string. If no argument is given it will return the whole file
(as done in the example).
<P>Now here is a new version of the phone numbers program that we made earlier: <PRE>import string
true = 1
false = 0
def print_numbers(numbers):
print "Telephone Numbers:"
for x in numbers.keys():
print "Name: ",x," \tNumber: ",numbers[x]
print
def add_number(numbers,name,number):
numbers[name] = number
def lookup_number(numbers,name):
if numbers.has_key(name):
return "The number is "+numbers[name]
else:
return name+" was not found"
def remove_number(numbers,name):
if numbers.has_key(name):
del numbers[name]
else:
print name," was not found"
def load_numbers(numbers,filename):
in_file = open(filename,"r")
while true:
in_line = in_file.readline()
if in_line == "":
break
in_line = in_line[:-1]
[name,number] = string.split(in_line,",")
numbers[name] = number
in_file.close()
def save_numbers(numbers,filename):
out_file = open(filename,"w")
for x in numbers.keys():
out_file.write(x+","+numbers[x]+"\n")
out_file.close()
def print_menu():
print '1. Print Phone Numbers'
print '2. Add a Phone Number'
print '3. Remove a Phone Number'
print '4. Lookup a Phone Number'
print '5. Load numbers'
print '6. Save numbers'
print '7. Quit'
print
</PRE><PRE>phone_list = {}
menu_choice = 0
print_menu()
while menu_choice != 7:
menu_choice = input("Type in a number (1-7):")
if menu_choice == 1:
print_numbers(phone_list)
elif menu_choice == 2:
print "Add Name and Number"
name = raw_input("Name:")
phone = raw_input("Number:")
add_number(phone_list,name,phone)
elif menu_choice == 3:
print "Remove Name and Number"
name = raw_input("Name:")
remove_number(phone_list,name)
elif menu_choice == 4:
print "Lookup Number"
name = raw_input("Name:")
print lookup_number(phone_list,name)
elif menu_choice == 5:
filename = raw_input("Filename to load:")
load_numbers(phone_list,filename)
elif menu_choice == 6:
filename = raw_input("Filename to save:")
save_numbers(phone_list,filename)
elif menu_choice == 7:
pass
else:
print_menu()
print "Goodbye"
</PRE>Notice that it now includes saving and loading files. Here is some output
of my running it twice: <PRE>> python tele2.py
1. Print Phone Numbers
2. Add a Phone Number
3. Remove a Phone Number
4. Lookup a Phone Number
5. Load numbers
6. Save numbers
7. Quit
Type in a number (1-7):2
Add Name and Number
Name:Jill
Number:1234
Type in a number (1-7):2
Add Name and Number
Name:Fred
Number:4321
Type in a number (1-7):1
Telephone Numbers:
Name: Jill Number: 1234
Name: Fred Number: 4321
Type in a number (1-7):6
Filename to save:numbers.txt
Type in a number (1-7):7
Goodbye
</PRE><PRE>> python tele2.py
1. Print Phone Numbers
2. Add a Phone Number
3. Remove a Phone Number
4. Lookup a Phone Number
5. Load numbers
6. Save numbers
7. Quit
Type in a number (1-7):5
Filename to load:numbers.txt
Type in a number (1-7):1
Telephone Numbers:
Name: Jill Number: 1234
Name: Fred Number: 4321
Type in a number (1-7):7
Goodbye
</PRE>
<P>The new portions of this program are: <PRE>def load_numbers(numbers,filename):
in_file = open(filename,"r")
while 1:
in_line = in_file.readline()
if len(in_line) == 0:
break
in_line = in_line[:-1]
[name,number] = string.split(in_line,",")
numbers[name] = number
in_file.close()
</PRE><PRE>def save_numbers(numbers,filename):
out_file = open(filename,"w")
for x in numbers.keys():
out_file.write(x+","+numbers[x]+"\n")
out_file.close()
</PRE>
<P>First we will look at the save portion of the program. First it creates a
file object with the command <CODE>open(filename,"w")</CODE>. Next it goes
through and creates a line for each of the phone numbers with the command
<CODE>out_file.write(x+","+numbers[x]+"\n")</CODE>. This writes out a line that
contains the name, a comma, the number and follows it by a newline.
<P>The loading portion is a little more complicated. It starts by getting a file
object. Then it uses a <CODE>while 1:</CODE> loop to keep looping until a
<CODE>break</CODE> statement is encountered. Next it gets a line with the line
<CODE>in_line = in_file.readline()</CODE>. The <CODE>getline</CODE> function
will return a empty string (len(string) == 0) when the end of the file is
reached. The <CODE>if</CODE> statement checks for this and <CODE>break</CODE>s
out of the <CODE>while</CODE> loop when that happens. Of course if the
<CODE>readline</CODE> function did not return the newline at the end of the line
there would be no way to tell if an empty string was an empty line or the end of
the file so the newline is left in what <CODE>getline</CODE> returns. Hence we
have to get rid of the newline. The line <CODE>in_line = in_line[:-1]</CODE>
does this for us by dropping the last character. Next the line
<CODE>[name,number] = string.split(in_line,",")</CODE> splits the line at the
comma into a name and a number. This is then added to the <CODE>numbers</CODE>
dictionary.
<P>
<H1><A name=SECTION001710000000000000000>Exercises</A> </H1>
<P>Now modify the grades program from section <A
href="http://www.honors.montana.edu/~jjc/easytut/easytut/node13.html#firstgrades">11</A>
so that is uses file IO to keep a record of the students.
<P>
<HR>
<!--Navigation Panel--><A
href="http://www.honors.montana.edu/~jjc/easytut/easytut/node18.html"
name=tex2html368><IMG align=bottom alt=next border=0 height=24
src="node17_files/next.png" width=37></A> <A
href="http://www.honors.montana.edu/~jjc/easytut/easytut/easytut.html"
name=tex2html364><IMG align=bottom alt=up border=0 height=24
src="node17_files/up.png" width=26></A> <A
href="http://www.honors.montana.edu/~jjc/easytut/easytut/node16.html"
name=tex2html358><IMG align=bottom alt=previous border=0 height=24
src="node17_files/prev.png" width=63></A> <A
href="http://www.honors.montana.edu/~jjc/easytut/easytut/node2.html"
name=tex2html366><IMG align=bottom alt=contents border=0 height=24
src="node17_files/contents.png" width=65></A> <BR><B>Next:</B> <A
href="http://www.honors.montana.edu/~jjc/easytut/easytut/node18.html"
name=tex2html369>Dealing with the imperfect</A> <B>Up:</B> <A
href="http://www.honors.montana.edu/~jjc/easytut/easytut/easytut.html"
name=tex2html365>Non-Programmers Tutorial For Python</A> <B>Previous:</B> <A
href="http://www.honors.montana.edu/~jjc/easytut/easytut/node16.html"
name=tex2html359>Revenge of the Strings</A> <B><A
href="http://www.honors.montana.edu/~jjc/easytut/easytut/node2.html"
name=tex2html367>Contents</A></B> <!--End of Navigation Panel-->
<ADDRESS>Josh Cogliati <A
href="mailto:jjc@honors.montana.edu">jjc@honors.montana.edu</A>
</ADDRESS></BODY></HTML>
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -