Example of reading and writing files and storage in Python Programming,
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
Articles you may be interested in:
- Python open read/Write File implementation script
- How to read and write Excel files using the xlrd module in python
- Interactive execution of python file read/write operations and linux shell variable commands
- Introduction to reading and writing Excel files using Python
- Example of reading and writing an INI file from python (reading and writing a file from python)
- Python file read/write operations
- Read and Write python files and use mysql to insert examples in batches (use python to operate mysql)
- Python read/Write File Operation example Program
- Python read/write Excel files
- Python uses ConfigObj to read and write the configuration file implementation code