This article mainly introduces the example of reading and writing files and memory in Python programming, including the example of using cPickle to store objects, for more information about reading and writing files and memory in Python programming, see this article. examples of using cPickle to store objects are provided. For more information, see
1. file writing and reading
#! /Usr/bin/python #-*-coding: UTF-8-*-# Filename: using_file.py # The file is created and read by s = '''. we are both wood leaders, you are not allowed to speak! ''' # Create a file and write the character f = file('test_file.txt ', 'w') f. write (s) f. close () # read the file and print f = file('test_file.txt ') while True: line = f. readline () # if the line length is 0, it indicates that the file has been read. if len (line) = 0: break # The default line break is also read, therefore, replace print line, f. close ()
Execution result:
We are all wood people. don't speak, don't move!
2. writing and reading of memory
#! /Usr/bin/python #-*-coding: UTF-8-*-# Filename using_pickle.py # use memory # load the memory module, as is followed by the alias # import pickle as p # The book says cPickle is much faster than pickle import cPickle as p listpickle = [1, 2, 2, 3] picklefile = 'picklefile. data 'F = file (picklefile, 'w') # write data such as p. dump (listpickle, f) f. close () del listpickle f = file (picklefile) # read data storedlist = p. load (f) print storedlist f. close ()
Execution result:
[1, 2, 2, 3]
Let's take a look at an example of using cPickle to store objects.
#!/usr/bin/python #Filename:pickling.py import cPickle as p shoplistfile = 'shoplist.data' shoplist = ['apple', 'mango', 'carrot'] f = file(shoplistfile, 'w') p.dump(shoplist, f) f.close() del shoplist f = file(shoplistfile) storedlist = p.load(f) print storedlist
The above is the detailed content of the sample code for reading and writing files and memory in Python programming. For more information, see other related articles in the first PHP community!