Remembering

Marcos Eimil Pardo marcos at nordesia.org
Mon Dec 22 13:49:26 EST 2003


Marcos Eimil Pardo escribió:

> MComp escribió:
> 
>> Hey guys, I'm another new to programming guy.  I have one quick
>> question.  How do you make a program not forget everything you input,
>> once it shuts down?  Thanks in advance.
> 
> 
> you can save read data to a file:
> 
> data=raw_input("type some data> ")
> # open a file to write text
> f=file("savedata","wt")
> # save data to file
> f.write(data)
> # close file
> f.close()
> 
> and when you reload your program you can read data from file:
> 
> # open a file to read text
> f=file("savedata","rt")
> # save data to file
> data=f.read()
> # close file
> f.close()
> 
> 
> well this is a very simplistic solution, if you want to save multiple 
> data, you must save it following some convention, for example if you 
> have read name and age, you can save it in a text file, with two lines, 
> the first with name and the second with age, and when you restart your 
> program you should read from file in the same order:
> 
> #to write multiple data item on multiple lines
> name=raw_input("name> ")
> age=raw_input("age> ")
> # open a file to write text
> f=file("savedata","wt")
> # save name to file
> f.write(name)
> # write newline character
> f.write("\n")
> # save age to file
> f.write(age)
> # close file
> f.close()
> 
> 
> #to read multiple data item on multiple lines
> # open a file to read text
> f=file("savedata","rt")
> # read name from file (name is in first line)
> # attention: we use readline to read one line, read() gets entire
> # file (read manual for more information)
> name = f.readline()
> # read age from file (age is in second line)
> age = f.readline()
> # age and name are strings terminated with a new-line character,
> # we may want to strip this last char, we can do it this way:
> age = age[:-1]
#oops too fast answer you can do better this way: (eliminating
#trailing whitespace characters, if present)
age=age.rstrip()
> name = name[:-1]
age=age.rstrip()

> # close file
> f.close()
> 
> hope, gives some help.
> greets, marcos.
> 
> 
> 







More information about the Python-list mailing list