python based tutorial: Python programming examples of reading and writing files and memory

This article describes the Python programming files and write memory sample, comprising the use of an example of a storage reservoir cPickle object, a friend in need can refer
to write and read files 1

#!/usr/bin/python 
# -*- coding: utf-8 -*- 
# Filename: using_file.py 
# 文件是创建和读取 
  
s = '''''我们都是木头人, 
不许说话不许动!'''
  
# 创建一个文件,并且写入字符 
f = file('test_file.txt', 'w') 
f.write(s) 
f.close() 
  
# 读取文件,逐行打印 
f = file('test_file.txt') 
while True: 
  line = f.readline() 
  # 如果line长度为0,说明文件已经读完了 
  if len(line) == 0: 
    break
  # 默认的换行符也读出来了,所以用逗号取代print函数的换行符 
  print line, 
f.close() 

Results of the:

我们都是木头人,
不许说话不许动!
 

2. The memory writing and reading

#!/usr/bin/python 
# -*- coding: utf-8 -*- 
# Filename using_pickle.py 
# 使用存储器 
  
#加载存储器模块,as后面是别名 
#import pickle as p 
#书上说cPickle比pickle快很多 
import cPickle as p 
  
listpickle = [1, 2, 2, 3] 
picklefile = 'picklefile.data'
  
f = file(picklefile, 'w') 
# 写如数据 
p.dump(listpickle, f) 
f.close() 
  
del listpickle 
  
f = file(picklefile) 
# 读取数据 
storedlist = p.load(f) 
print storedlist 
f.close() 

Results of the:

[1, 2, 2, 3]

Examples of the use of a look object storage reservoir cPickle

#!/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 

Thank you very much to read
in college chose the self-python, found that eating a working computer basic bad loss, this is not educated
can not do, can only be acquired to make up, then opened his own counter-attack outside the coding road, constantly learning python core knowledge, in-depth knowledge of basic computer learning, organized, if you are unwilling to mediocrity, it is with me outside of coding, growing it!
In fact, there is not only technical, more technical stuff than those, for example, how to make a fine programmer, rather than "Cock wire", the programmer itself is a noble presence, ah, is not it? [Click to join] want you want to be a noble person, come on!

Published 14 original articles · won praise 2 · Views 6673

Guess you like

Origin blog.csdn.net/chengxun03/article/details/105398127
Recommended