File processing
f= file (' Poem.txt ', ' W ')
# Open for ' W ' riting mode can be read mode (' R '), write mode (' W ') or Append mode (' a ')
F.write (poem) # Write text to file
F.close ()
f = File (' Poem.txt ')
# If no mode is specified, ' R ' ead mode was assumed by default
While True:
line = F.readline ()
If Len (line) = = 0: # Zero length indicates EOF
Break
Print line,
# Notice comma to avoid automatic newline added by Python
F.close () # Close the file
Note that because the content read from the file already ends with a newline character, we use commas on the print statement to eliminate the wrapping.
Storage device
Python provides a standard module, called Pickle. With it you can store any Python object in a file, and then you can take it out intact. This is referred to as a persistent storage object.
There is another module called Cpickle, which functions exactly the same as the Pickle module, except that it is written in C and therefore much faster (1000 times times faster than pickle). You can use either of them, and we'll use the Cpickle module here. Remember, we call these two modules short as pickle modules.
Import Cpickle as P
Shoplistfile = ' Shoplist.data '
# The name of the file where we'll store the object
Shoplist = [' Apple ', ' mango ', ' carrot ']
# Write to the file
f = File (Shoplistfile, ' W ')
P.dump (Shoplist, f) # Dump the object to a file stores objects in open files
F.close ()
Del shoplist # Remove the Shoplist
# Read back from the storage
f = File (Shoplistfile)
Storedlist = P.load (f)
Print Storedlist